Professional Documents
Culture Documents
SEMESTER : III
PYTHON INTRODUCTION
Python is one of the most popular programming languages in this era.
Python was developed by Guido van Rossum in the late eighties and early nineties at the
National Research Institute for Mathematics and Computer Science in the Netherlands.
Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-
68, SmallTalk, and Unix shell and other scripting languages.
Python source code is now available under the GNU General Public License (GPL).
Python 1.0 was released on 20 February, 1991.Python 2.0 was released on 16 October
2000 and had many major new features.
Python 3.0 was released on 3 December 2008.
APPLICATIONS OF PYTHON
Portable: Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
Extendable: You can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.
Databases support: Python provides interfaces to all major commercial databases.
GUI Programming: Python supports GUI applications that can be created and ported to
many system calls, libraries, and windows systems, such as Windows MFC, Macintosh,
and the X Window system of UNIX.
Scalable: Python provides a better structure and support for large programs than shell
scripting.
Python first compiles the source code (the statements in the file with extension .py file) into a
format known as byte code . Compilation is simply a translation step, and byte code is a
lower-level, and platform- independent, representation of your source code. Compiled code is
usually stored in .pyc files , and is regenerated when the source is updated.
Python translates each of your source statements into a group of byte code
instructions by decomposing them into individual steps. This byte code translation is
performed to speed execution —byte code can be run much more quickly than the original
source code statements.
The bytecode (.pyc file) is loaded into the Python runtime and interpreted by a Python Virtual
Machine , which is a piece of code that reads each instruction in the bytecode and executes
whatever operation is indicated. Byte code compilation is automatic, and the PVM is just part
of the Python system that you have installed on the machine. Technically, it's just the last step
of what is called the Python interpreter.
Once your program has been compiled to byte code (or the byte code has been loaded from
existing .pyc file), it is executed on the python virtual machine (PVM) (Cpython VM)
The standard Python implementation is a byte code virtual machine. This means that the
machine code (opcodes from your processor's opcode set) is not generated from your
program. The opcodes are only selected from the opcodes that are already compiled into the
virtual machine while the VM interprets the byte code. Hence Python execution is called as
―the Python interpreter.‖
Python is freely downloadable from the internet. There are multiple IDEs (Integrated
Development Environment) available for working with Python. Some of them are PyCharm,
LiClipse, IDLE etc. When you install Python, the IDLE editor will be available
automatically. Because, there are separate set of editors (IDE) available for different OS like
Window, UNIX, Ubuntu, Soloaris, Mac, etc. Apart from all these editors, Python program can be
run on command prompt also. The basic Python can be downloaded from the link:
https://www.python.org/downloads/
Python has rich set of libraries for various purposes like large-scale data processing,
predictive analytics, scientific computing etc. Based on one‘s need, the required packages can
be downloaded. But, there is a free open source distribution Anaconda, which simplifies
package management and deployment. To install Anaconda
https://anaconda.org/anaconda/python
Successful installation of anaconda provides you Python in a command prompt, the default
editor IDLE and also a browser-based interactive computing environment known as jupyter
notebook. The jupyter notebook allows the programmer to create notebook documents
including live code, interactive widgets, plots, equations, images etc.
WINDOWS INSTALLATION
Steps to install Python on Windows machine.
RUNNING PYTHON
A. RUNNING PYTHON INTERPRETER (REPL) INTERACTIVE SHELL MODE:
Python comes with an interactive interpreter (shell). When you type python in your
shell or command prompt, the python interpreter becomes active with a >>> prompt and
waits for your commands. When you type 2 + 3, Python took this command, calculated the
sum and then printed it. Again the same steps of reading, evaluating, printing happened for
the second command. This loop is called the read-eval-print-loop.
Now you can type any valid python expression at the prompt. Python reads the typed
expression, evaluates it and prints the result.
Python shell can be used a simple calculator. The recent output value is automatically stored
by the interpreter in special variable name ―_‖.The underscore variable is only in python
shell. It is NOT available in python scripts.
>>> hex(65)
'0x41'
>>> int(0x41)
65
Typing programs directly into the shell is highly inconvenient. Most programmers prefer to
use some sort of text editor that is part of an integrated development environment (IDE).
IDLE is an IDE (application) that comes as part of the standard Python installation package.
IDLE provides:
a text editor with syntax highlighting, autocompletion, and smart indentation,
a shell with syntax highlighting
an integrated debugger, which you should ignore for now.
When IDLE starts it will open a shell window into which you can type Python commands. It
will also provide you with a file menu and an edit menu.
• Goto File menu click on New File (CTRL+N) and write the code and save add.py
The IDE shipped with Anaconda is Spyder, which is more powerful than IDLE. It comes
with a good editor with great code completion and code analysis features, an interactive help
widget, Python and IPython consoles, a variables explorer and more. It can be launched from
the Anaconda's launcher.
And run this program by calling python test.py. Make sure you change to the directory where
you saved the file before doing it.
OBJECTS
Objects are the core things that Python programs manipulate. Every object has a type that
defines the kinds of things that programs can do with objects of that type. Types are either
scalar or non-scalar. Scalar objects are indivisible. Basic Scalar objects are numbers
(int,float,complex),Boolean, None type. Non Scalar objects are string,list,tuple,dictionary.
Every Object in python has a reference place in memory. Python assigns a long number as
identifier of the memory location to each object. This can be checked using id() function. The
data type of the object can be observed using the type() function.
>>> id(23)
1423339264
>>> type(23)
<class 'int'>
VARIABLES
Variables are reserved memory locations to store values. This means that when you create a
variable you reserve some space in memory. Variables provide a way to associate names
with objects.
Based on the data type of a variable, the interpreter allocates memory and decides what can
be stored in the reserved memory. Therefore, by assigning different data types to variables,
you can store integers, decimals or characters in these variables.
ASSIGNING VALUES TO VARIABLES
Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used to
assign values to variables. An assignment statement associates the name to the left of the =
symbol with the object denoted by the expression to the right of the =.
The operand to the left of the = operator is the name of the variable and the operand to the
right of the = operator is the value stored in the variable. For example –
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are assigned to the
same memory location. You can also assign multiple objects to multiple variables.
a, b, c = 1, 2.5, ”mothi”
Here, two integer objects with values 1 and 2 are assigned to variables a and b
respectively, and one string object with the value "john" is assigned to the variable c.
>>>x, y = 2, 3
binds x to 2 and y to 3.
>>>x, y = 2, 3
>>>x, y = y, x
>>>print( 'x =', x)
>>>print ('y =', y)
will print
x=3
y=2
After the assignment y = x, both refer to the same object. The identity function id() can be
used to find the identity of a variable. Every instance (object or variable) has an identity, i.e.
an integer which is unique within the script or program, i.e. other objects have different
identities.
>>> x = 42
>>> id(x)
10107136
>>> y = x
>>> id(x), id(y)
(10107136, 10107136)
>>> y = 78
>>> id(x), id(y)
(10107136, 10108288)
KEYWORDS
The following list shows the Python keywords. These are reserved words and you cannot use
them as constan-t or variable or any other identifier names. All the Python keywords contain
lowercase letters only. You can use help() utility on shell , followed by help>keywords to
find the keywords supported in python.
INPUT Function:
To get input from the user you can use the input function. When the input function is called
the program stops running the program, prompts the user to enter something at the keyboard
by printing a string called the prompt to the screen, and then waits for the user to press the
Enter key. The user types a string of characters and presses enter. Then the input function
returns that string and Python continues running the program by executing the next statement
after the input statement. Python provides the function input(). input has an optional
parameter, which is the prompt string.
A function chr() is used to convert an integer input into equivalent ASCII character.
>>> a=int(input("Enter an integer:"))
Enter an integer:65
>>> ch=chr(a)
>>> print("Character Equivalent of ", a, "is ",ch)
Character Equivalent of 65 is A
OUTPUT function:
We use the print() function to output data to the standard output device (screen). This
function prints the object/string written in function.
The print function can print an arbitrary number of values ("value1, value2, ..."), which are
separated by commas. These values are separated by blanks as sep separator is used between
the values. It defaults into a space character. After all values are printed, end is printed. It
defaults into a new line ( \n ).
To change this behaviour, we can assign an arbitrary string to the keyword parameter "end".
This string will be used for ending the output of the values of a print call:
>>> print("18","2","2018",sep='-')
18-2-2018
>>> company="Flipkart"
>>> address="Bangalore"
>>> print(company, address, sep='@')
Flipkart@Bangalore
The output of the print function is send to the standard output stream (sys.stdout) by default.
By redefining the keyword parameter "file" we can send the output into a different stream
e.g. sys.stderr or a file:
INDENTATION
Python does not support braces to indicate blocks of code for class and function definitions or
flow control. Blocks of code are denoted by line indentation. All the continuous lines
indented with same number of spaces would form a block. Python strictly follow indentation
rules to indicate the blocks.
Code blocks are identified by indentation rather than using symbols like curly braces.
Without extra symbols, programs are easier to read. Also, indentation clearly identifies which
block of code a statement belongs to. Of course, code blocks can consist of single statements,
too. It makes Python simplistic in nature and easy to read. It ensures that the visual structure
of a program is an accurate representation of the semantic structure of that program.
All statements with the same distance to the right belong to the same block of code. The
block ends at a line less indented or the end of the file. If a block has to be more deeply
nested, it is simply indented further to the right.
COMMENTS
Python has commenting capability for the purpose of in-code documentation. Comments start
with a #, and Python will render the rest of the line as a comment. Python also has extended
documentation capability, called docstrings. Docstrings can be one line, or multiline.
Python uses triple quotes at the beginning and end of the docstring.
DATA TYPES
Based on what value is stored in variables and what operations we can do on them, variables
are grouped into so called Data types.
Numbers: Number data types store numeric values. Number objects are created when you
assign a value to them. They are immutable objects and cant change their values. Python
supports different numerical types:
int is used to represent integers. Literals of type int are written in the way we typically denote
integers (e.g., -3 or 5 or 10002). There is only one "int" type,( which contains both "int" and
"long" from Python2) and is unlimited in size.
float is used to represent real numbers. Literals of type float always include a decimal point
(e.g., 3.0 or 3.17 or -28.72). (It is also possible to write literals of type float using scientific
notation. For example, the literal 1.6E3 stands for 1.6*103, i.e., it is the same as 1600.0.)
Complex numbers are written as <real part> + <imaginary part>j
For examples:
>>> x = 3 + 4j
>>> y = 2 - 3j
>>> z = x + y
>>> print(z)
(5+1j)
Strings: Strings in Python are identified as a contiguous set of characters represented in the
quotation marks. Python allows either pair of single or double quotes.
Lists: Lists are the most versatile of Python's compound sequence data types. A list contains
items separated by commas and enclosed within square brackets ([ ]). They are mutable.
Tuples: A tuple is sequence data type that is similar to the list. A tuple consists of a number
of values separated by commas. Tuples are enclosed within parenthesis and are immutable
Dictionary: Python's dictionaries are kind of hash-table of key-value pairs. A dictionary key
can be any Python type, but are usually numbers or strings. Values, on the other hand, can be
any arbitrary Python object. Dictionaries are enclosed within curly braces.
STRING
A string is a sequence (contiguous set of characters) of characters, enclosed either within a
pair of single quotes or double quotes. Python allows for either pairs of single or double quotes.
Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the
beginning of the string and working their way from -1 at the end. Each character of a string
corresponds to an index number, starting with zero as shown below –
S= ―Hello World‖
Character H e L l o w o r l d
index 0 1 2 3 4 5 6 7 8 9 10
They can also be enclosed in matching groups of three single or double quotes. In this case
they are called triple-quoted strings.
>>>name = "harish"
>>>print (type(name))
>>> <type 'str'>
SLICING OPERATION
A segment or a portion of a string is called as slice. Only a required number of characters can
be extracted from a string using colon (:) symbol. The basic syntax for slicing a string, st:
st[i:j:k]
This will extract character from ith character of st till (j-1)th character in steps of k. If first
index i is not present, it means that slice should start from the beginning of the string. If the
second index j is not mentioned, it indicates the slice should be till the end of the string. The
third parameter k, also known as stride, is used to indicate number of steps to be incremented
after extracting first character. The default value of stride is 1.
st="Hello World"
1. print("st[:] is", st[:]) #output Hello World
Starting from 0th index to 4th index (5 is exclusive), characters will be printed.
Starting from 3rd index to 7th index (8 is exclusive), characters will be printed.
5. print("st[7:] is ", st[7:]) #output is orld
Starting from 7th index to till the end of string, characters will be printed.
6. print(st[::2]) #outputs HloWrd
This example uses stride value as 2. So, starting from first character, every
alternative character (char+2) will be printed.
7. print("st[4:4] is ", st[4:4]) #gives empty string
Here,rd st[4:4] indicates, slicing should start from 4th character and end with (4-
1)=3 character, which is not possible. Hence the output would be an empty
string.
8. print(st[3:8:2]) #output is lo
Starting from 3rd character, till 7th character, every alternative index is considered.
Here, starting index is default value 0 and ending is -1 (corresponds to last character
in negative indexing). But, in slicing, as last index is excluded always, -1st character
is omitted and considered only up to -2nd character.
>>> st[3]='t'
TypeError: 'str' object does not support item assignment
Here, we are trying to change the 4th character (index 3 means, 4th character as the first index
is 0) to t. The error message clearly states that an assignment of new item (a string) is not
possible on string object. So, to achieve our requirement, we can create a new string using
slices of existing string as below –
>>> st= ―Hello World‖
BOOLEANS
int variables can be assigned any whole number. string variables can be assigned any
charecters. bool variables(otherwise known as booleans) are special. They can be assigned
only 2 values - True or False
>>>flag = True
>>>print( flag)
>>>True >>> var=12
>>>flag = False >>>bool(var)
>>>print( flag) True
>>>False >>>bool(0)
>>>type(True) False
>>> <type 'bool'>
>>> 5 == 5
True
>>> 5 == 6
False
COMPLEX
LISTS
Lists are the most versatile of Python's compound data types. A list contains items separated
by commas and enclosed within square brackets ([]). To some extent, lists are similar to
arrays in C. One difference between them is that all the items belonging to a list can be of
different data type. List are mutable objects, where its values can be changed.
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with
indexes starting at 0 in the beginning of the list and working their way to end -1. The plus
(+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.
For example −
TUPLE
A tuple is a sequence data type that is similar to the list. A tuple consists of a number of
values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and
their elements and size can be changed(mutable), while tuples are enclosed in parentheses ( (
) ) and cannot be updated(immutable).Tuples can be thought of as read-only lists.
DICTIONARY
Python's dictionaries are kind of hash table type. They work like associative arrays or hashes
found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type,
but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python
object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using
square braces (*+). For example –
dict={‗Name‘:‘varshini‘,‘Age‘:6,‘Grade‘:‘1st‘}
print(―dict[Name]:‖,dict[‗Name‘])
print(―dict[Age]:‖,dict[‗Age‘])
print(dict.keys())
print(dict.values())
print(dict.items())
dict[‗Age‘]=7
print(―After updation age is:‖,dict[‗Age‘])
Output:
dict[Name]: varshini
dict[Age]:6
After updation age is : 7
OPERATORS
ARITHMETIC OPERATORS
Arithmetic operators are used for doing common arithmetic operations like addition,
substraction etc. They are + - * / % **. For example, 2/3 is 2 divided by 3.
>>>12/2 >>>15/2
Out[26]: 6.0 Out[28]: 7.5
>>>12//2 >>>15//2
Out[27]: 6 Out[29]: 7
RELATIONAL OPERATORS
Relational operators include >, >=, <, <=, ==, !=. They take 2 operands and return a boolean
result(True or False). For example, the greater than operator (a > b) returns True if a is
bigger than b. Following table contains examples for other operators.
LOGICAL OPERATORS
There are three logical operators: not, or, and. 'not a' evaluates to the opposite of what 'a' is. 'a
and b' evaluates to True only if both a, b are True. 'a or b' evaluates to False if both a,b are
False. They behave exactly like !, ||, && operators in C.
a not a
True False
False True
a b a and b a or b
condition = True
print (not condition)
print (condition or False)
print (condition and False)
Out: False
Out: True
Out: False
ORDER OF OPERATIONS
When more than one operator appears in an expression, the order of evaluation depends on
the rules of precedence. For mathematical operators, Python follows mathematical
convention. The acronym PEMDAS is a useful way to remember the rules:
Parentheses have the highest precedence and can be used to force an expression to
evaluate in the order you want. Since expressions in parentheses are evaluated first, 2
* (3-1) is 4, and (1+1)**(5-2) is 8. You can also use parentheses to make an
expression easier to read, as in (minute * 100) / 60, even if it doesn't change the result.
Exponentiation has the next highest precedence, so 2**1+1 is 3, not 4, and 3*1**3 is
3, not 27.
Multiplication and Division have the same precedence, which is higher than
Addition and Subtraction, which also have the same precedence. So 2*3-1 is 5, not
4, and 6+4/2 is 8, not 5.
Operators with the same precedence are evaluated from left to right. So in the expression 5-3-
1 is 1, not 3 because the 5-3 happens first and then 1 is subtracted from 2.
Often times, instead of letting each line execute, we would need to selectively execute some
lines. This can be done by if, if-else, if-elif-else blocks. Python seperates blocks based on
their indentation. Unlike other langauges, python doesn‘t use curly brackets{} for creating
blocks.
if Boolean expression:
block of code
else:
block of code
Control flow
A second form of the if statement is alternative execution, in which there are two
possibilities and the condition determines which one gets executed.
if x%2==0:
print(―x is even‖)
else:
print(―x is odd‖)
Sometimes there are more than two possibilities and we need more than two branches.
chained conditional use elif(short form for else if).Also called as elif ladder
if x<y:
print(― x is less than y‖)
elif x>y:
print(―x is greater than y‖)
else:
print(―x and y are equal‖)
Nested Conditions
if x == y:
print 'x and y are equal'
else:
if x < y:
print 'x is less than y'
else:
print 'x is greater than y'
number = 24
result = "odd" if number % 2 != 0 else "even"
print(result)
Output: even
ITERATION
A generic iteration (also called looping) mechanism is depicted in figure. It begins with a test,
if it evaluates to True, the program executes the loop body once, and then goes back to
reevaluate the test. This process is repeated until the test evaluates to False, after which
control passes to the code following the iteration statement. Iteration is a processing repeating
some task. In a real time programming, we require a set of statements to be repeated certain
number of times and/or till a condition is met. Every programming language provides certain
constructs to achieve the repetition of tasks.
The while Statement
while condition:
statement_1
statement_2
…………….
statement_n
statements_after_while
Here, while is a keyword. The condition is evaluated first. Till its value remains true, the
statement_1 to statement_n will be executed. When the condition becomes false, the loop is
terminated and statements after the loop will be executed. Consider an example –
n=1
while n<=5:
print(n) #observe indentation
n=n+1
print("over")
1
2
3
4
5
over
In some situations, we deliberately want to come out of the loop even before the normal
termination of the loop. For this purpose break statement is used.
while True:
x=int(input("Enter a number:"))
if x>= 0:
print("You have entered ",x)
else:
print("You have entered a negative number!!")
break #terminates the loop
Sample output:
Enter a number:23
You have entered 23
Enter a number:-2
sum=0
count=0
while True:
x=int(input("Enter a number:"))
if x%2 !=0:
continue Read a number from the keyboard
else:
sum+=x
count+=1 If that number is odd, without doing anything
else, just move to next iteration for reading
if count==5: another number
break
If the number is even, add it to sum
print("Sum= ", sum) and increment the accumulator
variable. When accumulator crosses 5,
Sample Output: stop the program
Enter a number:13
Enter a number:12
Enter a number:4
Enter a number:5
Enter a number:-3
Enter a number:8
Enter a number:7
Enter a number:16
Enter a number:6
Sum= 46
Output:
H e l l o
FOR LOOP WITH RANGE FUNCTION
When we have a fixed set of numbers to iterate in a for loop, we can use a function range().
The function range() takes the following format –
for i in range(0,10,2):
print(i, end= ‗\t‘)
Output:
0 2 4 6 8
Ex4. Count and sum of elements of a list
total = 0
count=0
for x in [4, -2, 41, 34, 25]:
total = total + x
count= count+1
print(―Total:‖, total)
print(―Count:‖, count)
Pass statement
The pass statement is a null operation; nothing happens when it executes. The pass statement
is also useful in places where your code will eventually go, but has not been written yet i.e. in
stubs.It is used as a placeholder in decision constructs, looping constructs (for,while),
functions.
Syntax:
pass
Output
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
PYTHON PROGRAMMING
19ISE36
UNIT 2
Functions and Scoping : Functions and Scoping, Function calls, Type conversion, Type
coercion, Math functions, Functions as Objects ,Composition ,Variables and parameters are
local, global, Recursion, Modules, Files Handling, Directories
FUNCTIONS:
A function is a block of organized, reusable code that is used to perform a single, related
action. It is a named sequence of statement used to perform a specific task.
Once a function is written, it can be reused as and when required. So, functions are
also called reusable code.
Functions provide modularity for programming. A module represents a part of the
program. Usually, a programmer divides the main task into smaller sub tasks called
modules.
Code maintenance will become easy because of functions. When a new feature has to
be added to the existing software, a new function can be written and integrated into
the software.
When there is an error in the software, the corresponding function can be modified
without disturbing the other functions in the software.
The use of functions in a program will reduce the length of the program.
Python has many built-in functions like sqrt( ), etc. but you can also create your own
functions. These functions are called user-defined functions.
Objectname.methodname()
Classname.methodname()
Defining a Function
Rules to define a function in Python.
Function blocks begin with the keyword def followed by the function name and
parentheses ( ).
Any input parameters or arguments should be placed within these parentheses. You
can also define parameters inside these parentheses.
The code block within every function starts with a colon (:) and is indented.
A function that performs some task, but do not return any value to the calling function
is known as void function.
Syntax:
def functionname (parameters):
body of the function
return [expression]
Example:
def add(a,b):
"""This function sum the numbers"""
c=a+b
print c
return
Calling Function:
A function cannot run by its own. It runs only when we call it. While calling the function, we
should pass the necessary values to the function in the parentheses as:
add(5,12)
Example:
add(2,3)
add(2.3, 4.5)
add(a=2.3, b=4.5)
add(b=4.5, a=2.3)
Out: 5
Out: 6.8
Out: 6.8
Out: 6.8
x,y,z=calc(5,8)
print ("Addition=",x)
print ("Subtraction=",y)
print ("Multiplication=",z)
Map function
Map is built-in function that takes a function and applies it to a list..map() function returns a
list of the results after applying the given function to each item of a given iterable (list, tuple)
Syntax :
map(fun, iter)
Parameters :
fun : It is a function to which map passes each element of given iterable.
iter : It is a iterable which is to be mapped.
Each element in the list is used a parameter for len() and the results form a list. Notice that len
is passed and not len(). This is because, we are not calling len. We are just passing len to
map. map will internally call it
def add(a,b):
return a+b
print(list(map(add, [1,2,3,4], [10,20,30,40])))
def cube(number):
return number**3
print(list(map(cube, range(10))))
In Python, functions are considered as first class objects. It means we can use functions as
perfect objects. In fact when we create a function, the Python interpreter internally creates an
object. Since functions are objects, we can pass a function to another function just like we
pass an object (or value) to a function. The following possibilities are:
It is possible to assign a function to a variable.
It is possible to define one function inside another function.
It is possible to pass a function as parameter to another function.
It is possible that a function can return another function.
def first(msg):
print(msg)
first("Hello")
second = first
second("Hello")
Output
Hello
Hello
def display(f):
return "hai"+f
def message():
return " how r u?"
fun=display(message())
print(fun) Output: hai how r u?
def inc(x):
return x + 1
def dec(x):
return x - 1
def operate(func, x):
result = func(x)
return result
>>>func(inc,3)
>>>4
Output: how r u?
def display(st):
def message():
return "how r u? "
res=message()+st
return res
x=display("ISE")
print(x)
Pass by Object Reference in Python
In Python, we can observe both pass by value and pass by reference behaviour while passing
the actual parameters to the function definition. Python supports pass by object reference
unlike in C, C++.
Pass by Value:
Pass by value represents that a copy of the variable value is passed to the function and any
modifications to that value will not reflect outside the function. In python, the values are sent
to functions by means of object references. If we store a value into a variable as:
x=10
So, 10 is the object and x is the name of that object. Also, objects are created on heap memory
which is a very huge memory that depends on the RAM of our computer system.
This means another object 15 is created in memory and that object is referenced by the name
„x‟. The reason why another object is created in the memory is that the integer objects are
immutable (not modifiable). So in the function, when we display „x‟ value, it will display 15.
Once we come outside the function and display „x‟ value, it will display numbers of „x‟ inside
and outside the function, and we see different numbers since they are different objects.
Pass by Reference:
Pass by reference represents sending the reference or memory address of the variable to the
function. The variable value is modified by the function through memory address and hence
the modified value will reflect outside the function also. In python, lists and dictionaries are
mutable. That means, when we change their data, the same object gets modified and new
object is not created.
Example: A Python program to pass a list to a function and modify it.
def modify(a):
a.append(5)
print("inside",a,id(a))
a=[1,2,3,4]
modify(a)
print("outside",a,id(a))
Output:
inside [1, 2, 3, 4, 5] 45355616
outside [1, 2, 3, 4, 5] 45355616
Inside the function, we are appending a new element „5‟ to the list. Since, lists are mutable,
adding a new element to the same object is possible. Hence, append( ) method modifies the
same object.
a) Positional Arguments:
These are the arguments passed to a function in correct positional order. Here, the number of
arguments and their position in the function definition should match exactly with the number
and position of argument in the function call.
def attach(s1,s2):
s3=s1+s2
print (s3)
attach("New","Delhi") #Positional arguments
b) Keyword Arguments:
Keyword arguments are arguments that identify the parameters by their names. For example,
the definition of a function that displays grocery item and its price can be written as:
def grocery(item, price):
At the time of calling this function, we have to pass two values and we can mention which
value is for what. For example,
grocery(item=’sugar’, price=50.75)
Here, we are mentioning a keyword „item‟ and its value and then another keyword „price‟
and its value. Please observe these keywords are nothing but the parameter names which
receive these values. We can change the order of the arguments as:
grocery(price=88.00, item=’oil’)
def grocery(item,price):
print "item=",item
print "price=",price
grocery(item="sugar",price=50.75) # keyword arguments
grocery(price=88.00,item="oil") # keyword arguments
Output:
item= sugar
price= 50.75
item= oil
price= 88.0
c) Default Arguments:
We can mention some default value for the function parameters in the definition.
def grocery(item, price=40.00)
Here, the first argument is „item‟ whose default value is not mentioned. But the second
argument is „price‟ and its default value is mentioned to be 40.00. So, a default argument is an
argument that assumes a default value if a value is not provided in the function call for that
argument.
Example: def grocery(item,price=40.00):
print("item=",item)
print("price=",price)
grocery(item="sugar",price=50.75)
grocery(item="oil")
Output:
item= sugar
price= 50.75
item= oil
price= 40.0
Example:
def print_series(n=5):
for i in range(n):
print(i)
print ('calling with 3 as parameter')
print_series(3)
print ('calling without an actual parameter')
print_series()
Output:
Out: calling with 3 as parameter
Out: 0
Out: 1
Out: 2
Out: calling without an actual parameter
Out: 0
Out: 1
Out: 2
Out: 3
Out: 4
Example:
def add(farg,*args):
sum=0
for i in args:
sum=sum+i
print("sum is",sum+farg)
add(5,10)
add(5,10,20)
add(5,10,20,30)
Output: sum is 15
sum is 35
sum is 65
Example:
def max(*numbers):
result = -1
for number in numbers:
if number > result:
result = number
print(result)
Out: max(12,3,19,1)
19
When we declare a variable inside a function, it becomes a local variable. A local variable is a
variable whose scope is limited only to that function where it is created. That means the local
variable value is available only in that function and not outside of that function.
Example-1:
def myfunction():
a=10
print("Inside function",a) #display 10
myfunction()
print("outside function",a) # Error, not available
Output:
Inside function 10
outside function
NameError: name 'a' is not defined
When a variable is declared above a function, it becomes global variable. Such variables are
available to all the functions which are written after it.
Example-2:
a=11
def myfunction():
b=10
print("Inside function",a) #display global var
print("Inside function",b) #display local var
myfunction()
print("outside function",a) # available
print("outside function",b) # error
Output:
Inside function 11
Inside function 10
outside function 11
outside function
NameError: name 'b' is not defined
Sometimes, the global variable and the local variable may have the same name. In that case,
the function, by default, refers to the local variable and ignores the global variable. So, the
global variable is not accessible inside the function but outside of it, it is accessible.
Example-1:
a=11
def myfunction():
a=10
print("Inside function",a) # display local
myfunction()
print("outside function",a) # display global variable
Output:
Inside function 10
outside function 11
When the programmer wants to use the global variable inside a function, he can use the
keyword „global‟ before the variable in the beginning of the function body as:
global a
a=11
def myfunction():
global a
a=10
print("Inside function",a) # display global variable myfunction()
print("outside function",a) # display global variable
Output:
Inside function 10
outside function 10
Recursive Functions:
A function that calls itself is known as recursive function.
factorial(n) = n * factorial(n-1)
Example-1:
def factorial(n):
if n==0:
result=1
else:
result=n*factorial(n-1)
return result
for i in range(1,5):
Print("factorial of ",i,"is",factorial(i))
Output:
factorial of 1 is 1
factorial of 2 is 2
factorial of 3 is 6
factorial of 4 is 24
These functions are called anonymous because they are not declared in the standard
manner by using the def keyword. You can use the lambda keyword to create small
anonymous functions.
Lambda forms can take any number of arguments but return just one value in the form of
an expression. They cannot contain commands or multiple expressions.
An anonymous function cannot be a direct call to print because lambda requires an
expression.
Lambda functions have their own local namespace and cannot access variables other than
those in their parameter list and those in the global namespace.
Although it appears that lambda's are a one-line version of a function, they are not
equivalent to inline statements in C or C++, whose purpose is by passing function stack
allocation during invocation for performance reasons.
The syntax is:
lambda argument_list: expression
Example:
Normal function
f=lambda x:x*x
value = f(5) def square(x):
print (value) return x*x
Usage of lambda function with map() Function
The advantage of the lambda operator can be seen when it is used in combination with the
map() function. map() is a function with two arguments:
def fahrenheit(T):
return ((float(9)/5)*T + 32)
def celsius(T):
return (float(5)/9)*(T-32)
temp = (36.5, 37, 37.5,39)
F = list(map(fahrenheit, temp))
C =list(map(celsius, F))
By using lambda, we wouldn't have had to define and name the functions fahrenheit() and
celsius(). You can see this in the following interactive session:
map() can be applied to more than one list. The lists have to have the same length. map() will
apply its lambda function to the elements of the argument lists, i.e. it first applies to the
elements with the 0th index, then to the elements with the 1st index until the n-th index is
reached:
>>> a = [1,2,3,4]
>>> b = [17,12,11,10]
>>> c = [-1,-4,5,9]
>>> map(lambda
x,y:x+y,a,b) [18, 14, 14, 14]
>>> map(lambda
x,y,z:x+y+z,a,b,c) [17, 10, 19, 23]
Filter function
The function filter(function, list) offers an elegant way to filter out all the elements of a list,
for which the function function returns True. The function filter(f,l) needs a function f as its
first argument. f returns a Boolean value, i.e. either True or False. This function will be
applied to every element of the list l. Only if f returns True will the element of the list be
included in the result list.
reduce()
The reduce(fun,seq) function is used to apply a particular function passed in its argument to all
of the list elements mentioned in the sequence passed along. This function is defined in
“functools” module.
At first step, first two elements of sequence are picked and the result is obtained. Next step is
to apply the same function to the previously attained result and the number just succeeding the
second element and the result is again stored. This process continues till no more elements are
left in the container. The final returned result is returned and printed on console.
import functools
lis = [ 1 , 3, 5, 6, 2, ]
# using reduce to compute sum of list
print ("The sum of the list elements is : ",end="")
print (functools.reduce(lambda a,b : a+b,lis))
Output:
The sum of the list elements is : 17
The maximum element of the list is : 6
Function composition
Function composition is a way of combining functions such that the result of each function is
passed as the argument of the next function. For example, the composition of two functions f
and g is denoted f(g(x)) .
Output: 22
Modules:
A module is a file containing Python definitions and statements. The file name is the module
name with the suffix.py appended. Within a module, the module‟s name (as a string) is
available as the value of the global variable __name__. For instance, use your favourite text
editor to create a file called fibo.py in the current directory with the following contents:
Now enter the Python interpreter and import this module with the following command:
This does not enter the names of the functions defined in fibo directly in the current symbol
table; it only enters the module name fibo there. Using the module name you can access the
functions:
>>> fibo.fib(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>>fibo.__name__
'fibo'
from statement:
A module can contain executable statements as well as function definitions. These
statements are intended to initialize the module. They are executed only the first time the
module name is encountered in an import statement. (They are also run if the file is
executed as a script.)
Each module has its own private symbol table, which is used as the global symbol table by
all functions defined in the module. Thus, the author of a module can use global variables
in the module without worrying about accidental clashes with a user‟s global variables. On
the other hand, if you know what you are doing you can touch a module‟s global variables
with the same notation used to refer to its functions, modname.itemname.
Modules can import other modules. It is customary but not required to place all import
statements at the beginning of a module (or script, for that matter). The imported module
names are placed in the importing module‟s global symbol table.
mymodule .py
def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
import mymodule as mx
a = mx.person1["age"]
print(a)
mx.greeting(“Tom”)
There is a variant of the import statement that imports names from a module directly into
the importing module‟s symbol table. For example:
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
This does not introduce the module name from which the imports are taken in the local
symbol table (so in the example, fibo is not defined). Only fib() is imported.There is even a
variant to import all names that a module defines:
>>> from fibo import *
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
Built-in modules
import platform
x = platform.system()
print(x)
Variables are names (identifiers) that map to objects. A namespace is a dictionary of
variable names (keys) and their corresponding objects (values).
A Python statement can access variables in a local namespace and in the global
namespace. If a local and a global variable have the same name, the local variable
shadows the global variable.
Each function has its own local namespace. Class methods follow the same scoping
rule as ordinary functions.
Python makes educated guesses on whether variables are local or global. It assumes
that any variable assigned a value in a function is local.
Therefore, in order to assign a value to a global variable within a function, you must
first use the global statement.
The statement global VarName tells Python that VarName is a global variable. Python
stops searching the local namespace for the variable.
For example, we define a variable Money in the global namespace. Within the
functionMoney, we assign Money a value, therefore Python assumes Money as a local
variable. However, we accessed the value of the local variable Money before setting it,
so an UnboundLocalError is the result. Uncommenting the global statement fixes the
problem.
Math functions
Python has a math module that provides most of the familiar mathematical functions.
>>> degrees = 45
>>> radians = degrees / 360.0 * 2 * math.pi
>>> math.sin(radians)
0.707106781187
>>>math.cos(45*math.pi/180)
0.7071067811865476
>>> math.tan(45*math.pi/180)
0.9999999999999999
Directories
In a computer system, files are organized into directories. These may contain subdirectories
and files. We should import the OS module to be able to access the method.
>>> import os
To get the contents of a directory into a python list, we use the listdir() method.
>>> os.listdir()
['All Users', 'Default', 'Default User', 'desktop.ini', 'Public', 'TEMP', 'vandana']
>>>os.path.abspath(".\rpc.py")
'C:\\Users\\vandana\\Anaconda3\\Lib\\idlelib\\.\rpc.py'
>>> os.path.isdir("rpc.py")
False
>>> os.path.isdir("..\idlelib")
True
>>> os.path.isfile("rpc.py")
True
>>> os.path.isfile("..\idlelib")
False
>>>os.getcwd()
'C:\\Users\\vandana\\Anaconda3\\Lib\\idlelib
To get the path of current working directory as a bytes object, we use the method getcwdb().
>>>os.getcwdb()
b'C:\\Users\\vandana\\Anaconda3\\Lib\\idlelib'
>>> print(os.getcwd())
C:\Users\vandana\Anaconda3\Lib\idlelib
>>> os.chdir("C:\\Users")
>>> os.getcwd()
'C:\\Users'
>>> os.mkdir("ptest")
>>>os.rmdir('dirname')
>>> os.rename("ptest","python-test")
>>>os.remove('C:\\Users\\lifei\\Desktop\\Christmas 2017\\Readme.txt')
>>> os.path.exists('C:\\Users\\lifei\\Desktop\\Myfolder')
Pickling in Python
Pickle is used for serializing and de-serializing Python object structures, also called
marshalling or flattening. Serialization refers to the process of converting an object in memory
to a byte stream that can be stored on disk or sent over a network. Later on, this character
stream can then be retrieved and de-serialized back to a Python object. Any object in python
can be pickled so that it can be saved on disk.
Pickle “serialises” the object first before writing it to file. Pickling is a way to convert a
python object (list, dict, etc.) into a character stream. The idea is that this character stream
contains all the information necessary to reconstruct the object in another python script.
The pickle module implements binary protocols for serializing and de-serializing a
Python object structure. “Pickling” is the process whereby a Python object hierarchy is
converted into a byte stream, and “unpickling” is the inverse operation, whereby a byte stream
(from a binary file or bytes-like object) is converted back into an object hierarchy.
Application:
1) Saving a program's state data to disk so that it can carry on where it left off when restarted
(persistence)
4) Converting an arbitrary python object to a string so that it can be used as a dictionary key
(e.g. for caching & memoization).
5) Pickle is very useful for when you're working with machine learning algorithms, where you
want to save them to be able to make new predictions at a later time, without having to rewrite
everything or train the model all over again
Example:
import pickle
a = ['test value','test value 2','test value 3']
fileObject = open(“test_file”,'wb')
pickle.dump(a,fileObject)
fileObject.close()
fileObject = open(“test_file”,'r')
b = pickle.load(fileObject)
print(b)
print(a==b, type(b))
Output
['test value','test value 2','test value 3']
True <class „list‟>
Module 3
The most basic data structure in Python is the sequence. Each element of a sequence is assigned
a number - its position or index. The first index is zero, the second index is one, and so forth.
There are certain things you can do with all the sequence types. These operations include
indexing, slicing, adding, multiplying, and checking for membership. In addition, Python has
built-in functions for finding the length of a sequence and for finding its largest and smallest
elements.
Python Lists
The list is the most versatile datatype available in Python, which can be written as a list
of comma-separated values (items) between square brackets. Important thing about a list is that
the items in a list need not be of the same type. Creating a list is as simple as putting different
comma-separated values between square brackets.
For example : list1 = ['physics', 'chemistry', 1997, 2000]; list2 = [1, 2, 3, 4, 5 ]; list3 = ["a",
"b", "c", "d"]; Similar to string indices, list indices start at 0, and lists can be sliced,
concatenated and so on.
Accessing Values in Lists To access values in lists, use the square brackets for slicing along
with the index or indices to obtain value available at that index.
list2 = [1, 2, 3, 4, 5, 6, 7 ]
Delete List Elements To remove a list element, you can use either the del statement if you
know exactly which element(s) you are deleting.
Basic List Operations
Lists respond to the + and * operators much like strings; they mean concatenation and repetition
here too, except that the result is a new list, not a string.
Indexing, Slicing and Matrixes: Since lists are sequences, indexing and slicing work the
same way for lists as they do for strings. Assuming the following inputL=['C++'', 'Java',
'Python']
Built-in List Functions & Methods
2 len(list)
3 max(list)
4 min(list)
5 list(seq)
List len() Method : The len() method returns the number of elements in the list.
Parameters list - This is a list for which, number of elements are to be counted.
Return Value This method returns the number of elements in the list.
List max() Method : The max() method returns the elements from the list with maximum
value.
Parameters list - This is a list from which max valued element are to be returned.
Return Value This method returns the elements from the list with maximum value.
List min() Method : The method min() returns the elements from the list with minimum value.
syntax for min() method min(list)
Parameters list - This is a list from which min valued element is to be returned.
Return Value This method returns the elements from the list with minimum value.
List list() Method : The list() method takes sequence types and converts them to lists. This is
used to convert a given tuple into list.
Note: Tuple are very similar to lists with only difference that element values of a tuple can not
be changed and tuple elements are put between parentheses instead of square bracket. This
function also converts characters in a string into a list.
1 list.append(obj)
2 list.count(obj)
3 list.extend(seq)
4 list.index(obj)
5 list.insert(index, obj)
6 list.pop(obj=list[-1])
7 list.remove(obj)
9 list.sort([func])
List append() Method : The append() method appends a passed obj into the existing list.
syntax for append() method list.append(obj)
Return Value This method does not return any value but updates existing list.
List count() Method The count() method returns count of how many times obj occurs in list.
syntax for count() method list.count(obj)
Return Value This method returns count of how many times obj occurs in list.
List extend() Method The extend() method appends the contents of seq to list.
Return Value This method does not return any value but adds the content to an existing list.
List index() Method The index() method returns the lowest index in list that obj appears.
syntax for index() method list.index(obj)
Return Value This method returns index of the found object otherwise raises an exception
indicating that the value is not found.
List insert() Method The insert() method inserts object obj into list at offset index.
Parameters
index - This is the Index where the object obj need to be inserted.
Return Value This method does not return any value but it inserts the given element at the given
index.
List pop() Method The pop() method removes and returns last object or obj from the list.
syntax for pop() method list.pop(obj=list[-1])
Parameters obj - This is an optional parameter, index of the object to be removed from the list.
Return Value This method returns the removed object from the list.
Return Value This method does not return any value but removes the given object from the list.
List reverse() Method The reverse() method reverses objects of list in place.
Parameters NA
Return Value This method does not return any value but reverse the given object from the list.
List sort() Method The sort() method sorts objects of list, use compare function if given.
syntax for sort() method list.sort([func])
Parameters NA
Return Value This method does not return any value but reverses the given object from the list.
list.sort(reverse=True|False, key=myFunc)
>>> l=['ABC','abc','aBc','AbC']
>>> print(l.sort())
None
>>> l
>>> l= [1, 3, 4, 2]
>>>l.sort(reverse = True)
>>>l
[4,3,2,1]
def myFunc(e):
return len(e)
cars.sort(reverse=False, key=myFunc)
print(cars)
cars.sort(reverse=True, key=myFunc)
print(cars)
list.sort() sorts the list in-place, mutating the list indices, and returns None.
ls2.sort()
ls3=sorted(ls2)
List Comprehension
Comprehensions in Python provide us with a short and concise way to construct new sequences (such
as lists, set, dictionary etc.) using sequences which have been already defined.
List Comprehensions provide an elegant way to create new lists. The following is the basic
structure of a list comprehension:
output_list = [output_exp for member in iterable if (var satisfies this condition)]
expression is the member itself, a call to a method, or any other valid expression that returns
a value. In the example above, the expression i * i is the square of the member value.
member is the object or value in the list or iterable. In the example above, the member value
is i.
iterable is a list, set, sequence, generator, or any other object that can return its elements one
at a time. example, the iterable is range(10).
Note that list comprehension may or may not contain an if condition. List comprehensions can contain
multiple for (nested list comprehensions).
Reading multiple values using list comprehension
Output:
Cloning lists
Obtaining exact copy of an existing object (or list) is called ‘cloning’. These various ways of
copying
1. Using slicing technique
This is the easiest and the fastest way to clone a list. This method is considered when
we want to modify a list and also keep a copy of the original. In this we make a copy
of the list itself, along with the reference. This process is also called cloning.
Shallow copy
Shallow copy creates separate object but objects will have the reference to the same list
elements. Following code illustrates that when we add new element to the list, eleemnt will
be added to the list on which append was used but other list(copy of list) remains same.
But when we update the existing list element with new element, in shallow copy updating
modifies both the lists (because objects are different but they point/refer to same list
elements) as shown below
Deep copy
Deep copy is a process in which the copying process occurs recursively. It means first
constructing a new collection object and then recursively populating it with copies of
the child objects found in the original. In case of deep copy, a copy of object is copied
in other object. It means that any changes made to a copy of object do not reflect in
the original object. In python, this is implemented using “deepcopy()” function.
Deep copy
Shallow copy creates separate object and each object refers to separate list elemnts. Following
code illustrates that when we add new element to the list, eleemnt will be added to the list on
which append was used but other list(copy of list) remains same.
But when we update the existing list element with new element, in deep copy updating
modifies only the intended list but not the other copy list (because objects are different and
they point/refer to different list elements) as shown below
Dictionary
Each key is separated from its value by a colon (:), the items are separated by commas, and the
whole thing is enclosed in curly braces. An empty dictionary without any items is written with
just two curly braces, like this: {}. Keys are unique within a dictionary while values may not
be. The values of a dictionary can be of any type, but the keys must be of an immutable data
type such as strings, numbers, or tuples.
Accessing Values in Dictionary To access dictionary elements, you can use the familiar
square brackets along with the key to obtain its value.
If we attempt to access a data item with a key, which is not a part of the dictionary, we get an
error as follows-
Updating Dictionary You can update a dictionary by adding a new entry or a key-value pair,
modifying an existing entry, or deleting an existing entry as shown in a simple example given
below.
Delete Dictionary Elements You can either remove individual dictionary elements or clear
the entire contents of a dictionary. You can also delete entire dictionary in a single operation.
To explicitly remove an entire dictionary, just use the del statement. Following is a simple
example-
Properties of Dictionary Keys Dictionary values have no restrictions. They can be any
arbitrary Python object, either standard objects or user-defined objects. However, same is not
true for the keys.
(a) More than one entry per key is not allowed. This means no duplicate key is allowed.
When duplicate keys are encountered during assignment, the last assignment wins.
(b) Keys must be immutable. This means you can use strings, numbers or tuples as
dictionary keys but something like ['key'] is not allowed. Following is a simple example-
Built-in Dictionary Functions and Methods
Python includes the following dictionary functions −
1. len(dict)
Gives the total length of the dictionary. This would be equal to the number of items in
the dictionary.
2. str(dict)
3. type(variable)
Returns the type of the passed variable. If passed variable is dictionary, then it would
return a dictionary type.
Dictionary len() Method The method len() gives the total length of the dictionary. This would
be equal to the number of items in the dictionary.
Dictionary str() Method The method str() produces a printable string representation of a
dictionary.
Return Value This method returns the type of the passed variable.
1 dict.clear()
2 dict.copy()
3 dict.fromkeys()
Create a new dictionary with keys from seq and values set to value.
4 dict.get(key, default=None)
5 dict.has_key(key)
7 dict.keys()
Similar to get(), but will set dict[key] = default if key is not already in dict
9 dict.update(dict2)
10 dict.values()
Dictionary clear() Method The method clear() removes all items from the dictionary.
Parameters NA Return Value This method does not return any value.
Dictionary copy() Method The method copy() returns a shallow copy of the dictionary.
Parameters NA
Parameters
seq - This is the list of values which would be used for dictionary keys preparation.
value - This is optional, if provided then value would be set to this value
The method get() returns a value for the given key. If the key is not available then returns
default value None.
Parameters
Return Value : This method returns a value for the given key. If the key is not available, then
returns default value as None.
Dictionary items() Method The method items() returns a list of dict's (key, value) tuple pairs.
syntax for items() method dict.items()
Parameters NA
Return Value This method returns a list of all the available keys in the dictionary.
Dictionary setdefault() Method The method setdefault() is similar to get(), but will set
dict[key]=default if the key is not already in dict.
Parameters
Return Value This method returns the key value available in the dictionary and if given key is
not available then it will return provided default value.
Dictionary update() Method The method update() adds dictionary dict2's key-values pairs in
to dict. This function does not return anything.
Parameters NA
Return Value This method returns a list of all the values available in a given dictionary.
To retrieve both keys and values together we use items() on dictionary as follows:
The pop() method removes the item with the specified key name
Following code creates a dictionary where keys are numbers and values are squares of numbers
The popitem() method removes the last inserted item (in versions before 3.7, a random item
is removed instead):
Nested Dictionaries
A dictionary can also contain many dictionaries, this is called nested dictionaries.
Zip() is used to zip the lists, and dict() constructor is used to convert to dictionary, first
list elements will be taken as keys and 2nd list elements will be taken as values
Tuples
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The
main difference between the tuples and the lists is that the tuples cannot be changed unlike
lists. Tuples use parentheses, whereas lists use square brackets. Creating a tuple is as simple as
putting different comma-separated values. Optionally, you can put these comma-separated
values between parentheses also. For example
tup1 = ();
To write a tuple containing a single value you have to include a comma, even though there
tup1 = (50,)
Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.
To access values in tuple, use the square brackets for slicing along with the index or indices
Delete Tuple Elements Removing individual tuple elements is not possible. There is, of
course, nothing wrong with putting together another tuple with the undesired elements
discarded. To explicitly remove an entire tuple, just use the del statement. For example-
Tuples respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new tuple, not a strings.
Since tuples are sequences, indexing and slicing work the same way for tuples as they do for
strings, assuming the following input −
No Enclosing Delimiters
1 cmp(tuple1, tuple2)
3 max(tuple)
4 min(tuple)
5 tuple(seq)
Tuple len() Method The len() method returns the number of elements in the tuple.
Return Value This method returns the number of elements in the tuple.
Tuple max() Method The max() method returns the elements from the tuple with maximum
value.
Parameters tuple - This is a tuple from which max valued element to be returned.
Return Value This method returns the elements from the tuple with maximum value.
Tuple min() Method The min() method returns the elements from the tuple with minimum
value.
Return Value This method returns the elements from the tuple with minimum value.
Tuple tuple() Method The tuple() method converts a list of items into tuples.
tup.count(x) Returns how many times the element ‘x’ is found in tuple.
Returns the first occurrence of the element ‘x’ in tuple. Raises ValueError
tup.index(x)
if ‘x’ is not found in the tuple.
Python Sets
A set is an unordered collection of items. Every set element is unique (no duplicates) and must
be immutable (cannot be changed).
However, a set itself is mutable. We can add or remove items from it.
Sets can also be used to perform mathematical set operations like union, intersection,
symmetric difference, etc.
A set is created by placing all the items (elements) inside curly braces {}, separated by comma,
or by using the built-in set() function.
It can have any number of items and they may be of different types (integer, float, tuple, string
etc.). But a set cannot have mutable elements like lists, sets or dictionaries as its elements.
# set of integers
my_set = {1, 2, 3}
print(my_set)
# set of mixed datatypes
print(my_set)
Output
{1, 2, 3}
# Output: {1, 2, 3, 4}
my_set = {1, 2, 3, 4, 3, 2}
print(my_set)
# Output: {1, 2, 3}
print(my_set)
Output
{1, 2, 3, 4}
{1, 2, 3}
Empty curly braces {} will make an empty dictionary in Python. To make a set without any
elements, we use the set() function without any argument.
# initialize a with {}
a = {}
print(type(a))
a = set()
print(type(a))
Output
<class 'dict'>
<class 'set'>
Modifying a set in Python
Sets are mutable. However, since they are unordered, indexing has no meaning.
We cannot access or change an element of a set using indexing or slicing. Set data type does
not support it.
We can add a single element using the add() method, and multiple elements using
the update() method. The update() method can take tuples, lists, strings or other sets as its
argument. In all cases, duplicates are avoided.
# initialize my_set
my_set = {1, 3}
print(my_set)
# my_set[0]
# add an element
# Output: {1, 2, 3}
my_set.add(2)
print(my_set)
# Output: {1, 2, 3, 4}
my_set.update([2, 3, 4])
print(my_set)
# Output: {1, 2, 3, 4, 5, 6, 8}
print(my_set)
Output
{1, 3}
{1, 2, 3}
{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 8}
A particular item can be removed from a set using the methods discard() and remove().
The only difference between the two is that the discard() function leaves a set unchanged if the
element is not present in the set. On the other hand, the remove() function will raise an error in
such a condition (if element is not present in the set).
# initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)
# discard an element
# Output: {1, 3, 5, 6}
my_set.discard(4)
print(my_set)
# remove an element
# Output: {1, 3, 5}
my_set.remove(6)
print(my_set)
# discard an element
# Output: {1, 3, 5}
my_set.discard(2)
print(my_set)
# remove an element
# Output: KeyError
my_set.remove(2)
Output
{1, 3, 4, 5, 6}
{1, 3, 5, 6}
{1, 3, 5}
{1, 3, 5}
KeyError: 2
Similarly, we can remove and return an item using the pop() method.
Since set is an unordered data type, there is no way of determining which item will be popped.
It is completely arbitrary.
We can also remove all the items from a set using the clear() method.
# initialize my_set
my_set = set("HelloWorld")
print(my_set)
# pop an element
print(my_set.pop())
my_set.pop()
print(my_set)
# clear my_set
# Output: set()
my_set.clear()
print(my_set)
print(my_set)
Output
set()
Sets can be used to carry out mathematical set operations like union, intersection, difference
and symmetric difference. We can do this with operators or methods.
Let us consider the following two sets for the following operations.
>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}
Set Union
Union is performed using | operator. Same can be accomplished using the union() method.
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use | operator
# Output: {1, 2, 3, 4, 5, 6, 7, 8}
print(A | B)
Output
{1, 2, 3, 4, 5, 6, 7, 8}
>>> A.union(B)
{1, 2, 3, 4, 5, 6, 7, 8}
>>> B.union(A)
{1, 2, 3, 4, 5, 6, 7, 8}
Set Intersection
Set Intersection in
Python
Intersection of A and B is a set of elements that are common in both the sets.
# Intersection of sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# Output: {4, 5}
print(A & B)
Output
{4, 5}
>>> A.intersection(B)
{4, 5}
>>> B.intersection(A)
{4, 5}
Set Difference
Set Difference in
Python
Difference of the set B from set A(A - B) is a set of elements that are only in A but not in B.
Similarly, B - A is a set of elements in B but not in A.
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use - operator on A
# Output: {1, 2, 3}
print(A - B)
Output
{1, 2, 3}
>>> A.difference(B)
{1, 2, 3}
# use - operator on B
>>> B - A
{8, 6, 7}
>>> B.difference(A)
{8, 6, 7}
Symmetric Difference of A and B is a set of elements in A and B but not in both (excluding
the intersection).
Symmetric difference is performed using ^ operator. Same can be accomplished using the
method symmetric_difference().
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use ^ operator
# Output: {1, 2, 3, 6, 7, 8}
print(A ^ B)
Output
{1, 2, 3, 6, 7, 8}
>>> A.symmetric_difference(B)
{1, 2, 3, 6, 7, 8}
>>> B.symmetric_difference(A)
{1, 2, 3, 6, 7, 8}
There are many set methods, some of which we have already used above. Here is a list of all
the methods that are available with the set objects:
Method Description
# initialize my_set
my_set = set("apple")
# Output: True
print('a' in my_set)
# Output: False
Output
True
False
... print(letter)
...
l
Built-in Functions with Set
Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc. are
commonly used with sets to perform different tasks.
Function Description
Returns True if all elements of the set are true (or if the set is
all()
empty).
Returns True if any element of the set is true. If the set is empty,
any()
returns False.
Returns an enumerate object. It contains the index and value for all
enumerate()
the items of the set as a pair.
Returns a new sorted list from elements in the set(does not sort the
sorted()
set itself).
Frozenset is a new class that has the characteristics of a set, but its elements cannot be changed
once assigned. While tuples are immutable lists, frozensets are immutable sets.
Sets being mutable are unhashable, so they can't be used as dictionary keys. On the other hand,
frozensets are hashable and can be used as keys to a dictionary.
# Frozensets
# initialize A and B
A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])
>>> A.isdisjoint(B)
False
>>> A.difference(B)
frozenset({1, 2})
>>> A | B
frozenset({1, 2, 3, 4, 5, 6})
>>> A.add(3)
...
Python Strings
A string is a sequence of characters.
Strings can be created by enclosing characters inside a single quote or double-quotes. Even
triple quotes can be used in Python but generally used to represent multiline strings and
docstrings.
my_string = 'Hello'
print(my_string)
my_string = "Hello"
print(my_string)
my_string = '''Hello'''
print(my_string)
print(my_string)
Hello
Hello
Hello
Hello, welcome to
We can access individual characters using indexing and a range of characters using slicing.
Index starts from 0. Trying to access a character out of index range will raise an IndexError.
The index must be an integer. We can't use floats or other types, this will result into TypeError.
The index of -1 refers to the last item, -2 to the second last item and so on. We can access a
range of items in a string by using the slicing operator :(colon).
str = 'programiz'
#first character
#last character
str = programiz
str[0] = p
str[-1] = z
str[1:5] = rogr
str[5:-2] = am
If we try to access an index out of the range or use numbers other than an integer, we will get
errors.
>>> my_string[15]
...
>>> my_string[1.5]
...
Slicing can be best visualized by considering the index to be between the elements as shown
below.
If we want to access a range, we need the index that will slice the portion from the string.
String Slicing in
Python
Strings are immutable. This means that elements of a string cannot be changed once they have
been assigned. We can simply reassign different strings to the same name.
...
>>> my_string
'Python'
We cannot delete or remove characters from a string. But deleting the string entirely is possible
using the del keyword.
...
>>> my_string
...
There are many operations that can be performed with strings which makes it one of the most
used data types in Python.
To learn more about the data types available in Python visit: Python Data Types
The + operator does this in Python. Simply writing two string literals together also
concatenates them.
The * operator can be used to repeat the string for a given number of times.
str1 = 'Hello'
str2 ='World!'
# using +
# using *
str1 * 3 = HelloHelloHello
Writing two string literals together also concatenates them like + operator.
'Hello World!'
... 'World')
>>> s
'Hello World'
We can iterate through a string using a for loop. Here is an example to count the number of 'l's
in a string.
count = 0
if(letter == 'l'):
count += 1
print(count,'letters found')
3 letters found
We can test if a substring exists within a string or not, using the keyword in.
True
False
Escape Sequence
If we want to print a text like He said, "What's there?", we can neither use single quotes nor
double quotes. This will result in a SyntaxError as the text itself contains both single and double
quotes.
...
...
One way to get around this problem is to use triple quotes. Alternatively, we can use escape
sequences.
An escape sequence starts with a backslash and is interpreted differently. If we use a single
quote to represent a string, all the single quotes inside the string must be escaped. Similar is
the case with double quotes. Here is how it can be done to represent the above text.
\\ Backslash
\a ASCII Bell
\b ASCII Backspace
\f ASCII Formfeed
\n ASCII Linefeed
C:\Python32\Lib
This is printed
in two lines
Sometimes we may wish to ignore the escape sequences inside a string. To do this we can
place r or R in front of the string. This will imply that it is a raw string and any escape sequence
inside it will be ignored.
This is a
good example
The format() method that is available with the string object is very versatile and powerful in
formatting strings. Format strings contain curly braces {} as placeholders or replacement fields
which get replaced.
# default(implicit) order
print(default_order)
print(positional_order)
print(keyword_order)
1 capitalize()
2 center(width, fillchar)
Returns a space-padded string with the original string centered to a total of width
columns.
Counts how many times str occurs in string or in a substring of string if starting
index beg and ending index end are given.
4 decode(encoding='UTF-8',errors='strict')
Decodes the string using the codec registered for encoding. encoding defaults to
the default string encoding.
5 encode(encoding='UTF-8',errors='strict')
Determines if string or a substring of string (if starting index beg and ending index
end are given) ends with suffix; returns true if so and false otherwise.
7 expandtabs(tabsize=8)
Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not
provided.
Determine if str occurs in string or in a substring of string if starting index beg and
ending index end are given returns index if found and -1 otherwise.
10 isalnum()
Returns true if string has at least 1 character and all characters are alphanumeric
and false otherwise.
11 isalpha()
Returns true if string has at least 1 character and all characters are alphabetic and
false otherwise.
12 isdigit()
13 islower()
Returns true if string has at least 1 cased character and all cased characters are in
lowercase and false otherwise.
14 isnumeric()
Returns true if a unicode string contains only numeric characters and false
otherwise.
15 isspace()
Returns true if string contains only whitespace characters and false otherwise.
16 istitle()
17 isupper()
Returns true if string has at least one cased character and all cased characters are in
uppercase and false otherwise.
18 join(seq)
19 len(string)
20 ljust(width[, fillchar])
21 lower()
22 lstrip()
23 maketrans()
24 max(str)
Returns the max alphabetical character from the string str.
25 min(str)
Replaces all occurrences of old in string with new or at most max occurrences if
max given.
27 rfind(str, beg=0,end=len(string))
29 rjust(width,[, fillchar])
30 rstrip()
31 split(str="", num=string.count(str))
Splits string according to delimiter str (space if not provided) and returns list of
substrings; split into at most num substrings if given.
32 splitlines( num=string.count('\n'))
Splits string at all (or num) NEWLINEs and returns a list of each line with
NEWLINEs removed.
33 startswith(str, beg=0,end=len(string))
Determines if string or a substring of string (if starting index beg and ending index
end are given) starts with substring str; returns true if so and false otherwise.
34 strip([chars])
35 swapcase()
36 title()
Returns "titlecased" version of string, that is, all words begin with uppercase and
the rest are lowercase.
37 translate(table, deletechars="")
38 upper()
39 zfill (width)
Returns original string leftpadded with zeros to a total of width characters; intended
for numbers, zfill() retains any sign given (less one zero).
40 isdecimal()
Returns true if a unicode string contains only decimal characters and false
otherwise.
Module 4
For instance, an object could represent a person with properties like a name, age, and
address and behaviors such as walking, talking, breathing, and running. Or it could
represent an email with properties like a recipient list, subject, and body and behaviors like
adding attachments and sending.
Put another way, object-oriented programming is an approach for modeling concrete, real-
world things, like cars, as well as relations between things, like companies and employees,
students and teachers, and so on. OOP models real-world entities as software objects that
have some data associated with them and can perform certain functions.
Data sharing Global data is shared among the Data is shared among the
functions in the program. objects through the
member functions.
One of the popular approaches to solve a programming problem is by creating objects. This
is known as Object-Oriented Programming (OOP).
attributes
behavior
Class − A user-defined prototype for an object that defines a set of attributes that
characterize any object of the class. The attributes are data members (class variables and
instance variables) and methods, accessed via dot notation.
Class variable − A variable that is shared by all instances of a class. Class variables are
defined within a class but outside any of the class's methods. Class variables are not used
as frequently as instance variables are.
Data member − A class variable or instance variable that holds data associated with a
class and its objects.
Instance variable − A variable that is defined inside a method and belongs only to the
current instance of a class.
Inheritance − The transfer of the characteristics of a class to other classes that are derived
from it.
Instance − An individual object of a certain class. An object obj that belongs to a class
Circle, for example, is an instance of the class Circle.
Object − A unique instance of a data structure that's defined by its class. An object
comprises both data members (class variables and instance variables) and methods.
Class
The class can be defined as a collection of objects. It is a logical entity that has some
specific attributes and methods. For example: if you have an employee class, then it should
contain an attribute and method, i.e. an email id, name, age, salary, etc.
Syntax
class ClassName:
<statement-1>
.
.
<statement-N>
Object
The object is an entity that has state and behavior. It may be any real-world object like the
mouse, keyboard, chair, table, pen, etc.
Everything in Python is an object, and almost everything has attributes and methods. All
functions have a built-in attribute __doc__, which returns the docstring defined in the
function source code.
When we define a class, it needs to create an object to allocate the memory. Consider the
following example.
Example:
class car:
def __init__(self,modelname, year):
self.modelname = modelname
self.year = year
def display(self):
print(self.modelname,self.year)
c1 = car("Toyota", 2016)
c1.display()
Method
The method is a function that is associated with an object. In Python, a method is not unique
to class instances. Any object type can have methods.
Inheritance
By using inheritance, we can create a class which uses all the properties and behavior of
another class. The new class is known as a derived class or child class, and the one whose
properties are acquired is known as a base class or parent class.
Polymorphism
Polymorphism contains two words "poly" and "morphs". Poly means many, and morph
means shape. By polymorphism, we understand that one task can be performed in different
ways. For example - you have a class animal, and all animals speak. But they speak
differently. Here, the "speak" behavior is polymorphic in a sense and depends on the
animal. So, the abstract "animal" concept does not actually "speak", but specific animals
(like dogs and cats) have a concrete implementation of the action "speak".
Encapsulation
Data Abstraction
Data abstraction and encapsulation both are often used as synonyms. Both are nearly
synonyms because data abstraction is achieved through encapsulation.
Abstraction is used to hide internal details and show only functionalities. Abstracting
something means to give names to things so that the name captures the core of what a
function or a whole program does.
Python Class and Objects
Suppose a class is a prototype of a building. A building contains all the details about the
floor, rooms, doors, windows, etc. we can make as many buildings as we want, based on
these details. Hence, the building can be seen as a class, and we can create as many objects
of this class.
On the other hand, the object is the instance of a class. The process of creating an object
can be called instantiation.
In Python, a class can be created by using the keyword class, followed by the class name.
The syntax to create a class is given below.
Syntax
class ClassName:
#statement_suite
In Python, we must notice that each class is associated with a documentation string which
can be accessed by using <class-name>.__doc__. A class contains a statement suite
including fields, constructor, function, etc. definition.
Consider the following example to create a class Employee which contains two fields as
Employee id, and name.
The class also contains a function display(), which is used to display the information of
the Employee.
Example
class Employee:
id = 10
name = "Devansh"
def display (self):
print(self.id,self.name)
Here, the self is used as a reference variable, which refers to the current class object. It is
always the first argument in the function definition. However, using self is optional in the
function call.
The self-parameter
The self-parameter refers to the current instance of the class and accesses the class
variables. We can use anything instead of self, but it must be the first parameter of any
function which belongs to the class.
A class needs to be instantiated if we want to use the class attributes in another class or
method. A class can be instantiated by calling the class using the class name.
<object-name> = <class-name>(<arguments>)
The following example creates the instance of the class Employee defined in the above
example.
Example
class Employee:
id = 10
name = "John"
def display (self):
print("ID: %d \nName: %s"%(self.id,self.name))
# Creating a emp instance of Employee class
emp = Employee()
emp.display()
We can delete the properties of the object or object itself by using the del keyword.
Consider the following example.
Example
class Employee:
id = 10
name = "John"
def display(self):
print("ID: %d \nName: %s" % (self.id, self.name))
# Creating a emp instance of Employee class
emp = Employee()
Python Constructor
A constructor is a special type of method (function) which is used to initialize the instance
members of the class.
In C++ or Java, the constructor has the same name as its class, but it treats constructor
differently in Python. It is used to create an object.
Parameterized Constructor
Non-parameterized Constructor
Constructor definition is executed when we create the object of this class. Constructors also
verify that there are enough resources for the object to perform any start-up task.
We can pass any number of arguments at the time of creating the class object, depending
upon the __init__() definition. It is mostly used to initialize the class attributes. Every class
must have a constructor, even if it simply relies on the default constructor.
Example
class Employee:
def __init__(self, name, id):
self.id = id
self.name = name
def display(self):
print("ID: %d \nName: %s" % (self.id, self.name))
emp1.display()
The first method __init__() is a special method, which is called class constructor or
initialization method that Python calls when you create a new instance of this class.
You declare other class methods like normal functions with the exception that the first
argument to each method is self. Python adds the self argument to the list for you; you do
not need to include it when you call the methods.
The constructor is called automatically when we create the object of the class. Consider the
following example.
Example
class Student:
count = 0
def __init__(self):
Student.count = Student.count + 1
s1=Student()
s2=Student()
s3=Student()
print("The number of students:",Student.count)
The non-parameterized constructor uses when we do not want to manipulate the value or
the constructor that has only self as an argument. Consider the following example.
Example
class Student:
# Constructor - non parameterized
def __init__(self):
print("This is non parametrized constructor")
def show(self,name):
print("Hello",name)
student = Student()
student.show("John")
Example
class Student:
# Constructor - parameterized
def __init__(self, name):
print("This is parametrized constructor")
self.name = name
def show(self):
print("Hello",self.name)
student = Student("John")
student.show()
When we do not include the constructor in the class or forget to declare it, then that becomes
the default constructor. It does not perform any task but initializes the objects. Consider the
following example.
Example
class Student:
roll_num = 101
name = "Joseph"
def display(self):
print(self.roll_num,self.name)
st = Student()
st.display()
Output:
101 Joseph
Example
class Student:
def __init__(self):
print("The First Constructor")
def __init__(self):
print("The second contructor")
st = Student()
Output:
In the above code, the object st called the second constructor whereas both have the same
configuration. The first method is not accessible by the st object. Internally, the object of
the class will always call the last constructor if the class has multiple constructors.
The built-in functions defined in the class are described in the following table.
SN Function Description
Example
class Student:
def __init__(self, name, id, age):
self.name = name
self.id = id
self.age = age
print(hasattr(s, 'id'))
# deletes the attribute age
delattr(s, 'age')
# this will give an error since the attribute age has been deleted
print(s.age)
Output:
John
23
True
AttributeError: 'Student' object has no attribute 'age'
Along with the other attributes, a Python class also contains some built-in class attributes
which provide information about the class.
SN Attribute Description
Example
class Student:
def __init__(self,name,id,age):
self.name = name;
self.id = id;
self.age = age
def display_details(self):
print("Name:%s, ID:%d, age:%d"%(self.name,self.id))
s = Student("John",101,22)
print(s.__doc__)
print(s.__dict__)
print(s.__module__)
Output:
None
{'name': 'John', 'id': 101, 'age': 22}
__main__
Class Attributes: class attributes are common to all instances/objects of a class. Class
attributes are defined in class definition but outside __init__() method.
Instance Attributes: Instance attributes are specific to each object and they change from
one object to other object. These are defined in __init__() method.
Static method: Methods defined to include general definition. Static methods doesn’t work
with instance or class attributes
Access modifiers
Access modifiers limit access to the variables and functions of a class. Python uses three
types of access modifiers; they are - private, public and protected.
Public members
Public members are accessible anywhere from the class. All the member variables of the
class are by default public.
Protected members
Protected members are accessible within the class and also available to its sub-classes. To
define a protected member, prefix the member name with a single underscore “_”. In
python implementation of protected is same as public except that protected is defined with
prefix of _ .
Private members
Private members are accessible within the class. To define a private member, prefix the
member name with a double underscore “__”.
Private data members cannot be accessed outside the class definition as well in the sub classes.
They can only be accessed within the class definition as shown below
Python Inheritance
The method of inheriting the properties of parent class into a child class is known as
inheritance. It is an OOP concept. Following are the benefits of inheritance.
Code reusability- we do not have to write the same code again and again, we can just inherit
the properties we need in a child class.
It represents a real world relationship between parent class and child class.
It is transitive in nature. If a child class inherits properties from a parent class, then all other
sub-classes of the child class will also inherit the properties of the parent class.
In inheritance, the child class acquires the properties and can access all the data members
and functions defined in the parent class. A child class can also provide its specific
implementation to the functions of the parent class.
1. Single
2. Multiple
3. Multilevel
4. Hierarchical
5. Hybrid
Single Inheritance
In single inheritance, a child class inherits all the properties of a parent class.
Syntax
class derived-class(base class):
<class-suite>
A class can inherit multiple classes by mentioning all of them inside the bracket. Consider
the following syntax.
Syntax
class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
<class - suite>
Example 1
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
d.speak()
Output:
dog barking
Animal Speaking
Multi-Level inheritance
Syntax
class class1:
<class-suite>
class class2(class1):
<class suite>
class class3(class2):
<class suite>
.
.
Example
class Animal:
def speak(self):
print("Animal Speaking")
#The child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
#The child class Dogchild inherits another child class Dog
class DogChild(Dog):
def eat(self):
print("Eating bread...")
d = DogChild()
d.bark()
d.speak()
d.eat()
Output:
dog barking
Animal Speaking
Eating bread...
Syntax
class Base1:
<class-suite>
class Base2:
<class-suite>
.
.
.
class BaseN:
<class-suite>
Output:
30
200
0.5
In this type of inheritance, more than one child classes inherit all the properties of
the same parent class
class Parent:
def func1(self):
class Child(Parent):
def func2(self):
print("this is function 2")
class Child2(Parent):
def func3(self):
ob = Child()
ob1 = Child2()
ob.func1()
ob.func2()
Hybrid inheritance is a combination of multiple and multilevel inheritance. More than one
child class inherits a parent class. Those two child class, in turn, acts as the parent class for
a grandchild class as shown in the below image.
class Parent:
def func1(self):
class Child(Parent):
def func2(self):
class Child1(Parent):
def func3(self):
def func4(self):
print(" this is function 4")
ob = Child3()
ob.func1()
The issubclass(sub, sup) method is used to check the relationships between the specified
classes. It returns true if the first class is the subclass of the second class, and false
otherwise.
Example
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(issubclass(Derived,Calculation2))
print(issubclass(Calculation1,Calculation2))
Output:
True
False
The isinstance (obj, class) method
The isinstance() method is used to check the relationship between the objects and classes.
It returns true if the first parameter, i.e., obj is the instance of the second parameter, i.e.,
class.
Example
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(isinstance(d,Derived))
Output:
True
class Parent:
def func1(self):
class Child(Parent):
def func2(self):
Super().func1()
ob = Child()
ob.func2()
Redefining Methods:
If you want your subclass to redefine a method of the parent class (so that it does something
different), you can just type a new definition for this method’s name in the subclass.
If you want the old code to be executed in addition to your new code for some method, then
you must explicitly call the parent’s version of the method.
parentClass.methodName(self, a, b, c)
If you want your subclass to redefine a method of the parent class (so that it does something
different), you can just type a new definition for this method’s name in the subclass.
If you want the old code to be executed in addition to your new code for some method, then
you must explicitly call the parent’s version of the method.
parentClass.methodName(self, a, b, c)
The only time you ever explicitly pass ‘self’ as an argument is when calling a
method of an ancestor.
In this case, it’s very common that you will want to execute the ancestor’s __init__
method in addition to your new commands.
You’ll often see something like this in the __init__ method of subclasses:
parentClass.__init__(self, x, y)
class User:
self.name = name
def printName(self):
class Programmer(User):
def __init__(self,fname,lname):
User.__init__(self,fname)
self.last_name =lname
def printName(self):
print("FullName",self.name,self.last_name)
def display(self):
User.printName(self)
brian = User("brian")
brian.printName()
diana = Programmer("Diana","Peter")
diana.printName()
diana.display()
Output:
Name = brian
Name = Diana
Polymorphism in Python
Polymorphism is taken from the Greek words Poly (many) and morphism (forms). It means
that the same function name can be used for different types. This makes programming more
intuitive and easier.
A child class inherits all the methods from the parent class. However, in some situations,
the method inherited from the parent class doesn’t quite fit into the child class. In such
cases, you will have to re-implement method in the child class.
There are different methods to use polymorphism in Python. You can use different
function, class methods or objects to define polymorphism.
It is possible for us to change the default behavior of Python's built-in functions. We only
have to define the corresponding special method in our class.
Let us demonstrate this using Python's len() function on our Purchase class:
class Purchase:
def __init__(self, basket, buyer):
self.basket = list(basket)
self.buyer = buyer
def __len__(self):
return 10;
Depending on how the function has been defined, we can call it with zero, one, two, or even
many parameters. This is referred to as "function overloading".
Function overloading is further divided into two types: overloading built-in functions and
overloading custom functions.
You can create a function that can take any object, allowing for polymorphism.
Let’s take an example and create a function called “func()” which will take an object which
we will name “obj”. Now, let’s give the function something to do that uses the ‘obj’ object
we passed to it. In this case, let’s call the methods type() and color(), each of which is
defined in the two classes ‘Tomato’ and ‘Apple’. Now, you have to create instantiations of
both the ‘Tomato’ and ‘Apple’ classes if we don’t have them already:
class Tomato():
def type(self):
print("Vegetable")
def color(self):
print("Red")
class Apple():
def type(self):
print("Fruit")
def color(self):
print("Red")
def func(obj):
obj.type()
obj.color()
obj_tomato = Tomato()
obj_apple = Apple()
func(obj_tomato)
func(obj_apple)
Output:
Vegetable
Red
Fruit
Red
Python uses two different class types in the same way. Here, you have to create a for
loop that iterates through a tuple of objects. Next, you have to call the methods without
being concerned about which class type each object is. We assume that these methods
actually exist in each class.
class India():
def capital(self):
print("New Delhi")
def language(self):
print("Hindi and English")
class USA():
def capital(self):
print("Washington, D.C.")
def language(self):
print("English")
obj_ind = India()
obj_usa = USA()
for country in (obj_ind, obj_usa):
country.capital()
country.language()
Output:
New Delhi
Hindi and English
Washington, D.C.
English
Operator Overloading
Python allows us to change the default behavior of an operator depending on the operands
that we use. This practice is referred to as "operator overloading".
The functionality of Python operators depends on built-in classes. However, the same
operator will behave differently when applied to different types. A good example is the "+"
operator. This operator will perform an arithmetic operation when applied on two numbers,
will concatenate two strings, and will merge two lists.
This feature in Python that allows the same operator to have different meaning according
to the context is called operator overloading.
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
p1 = Point(1, 2)
p2 = Point(2, 3)
print(p1+p2)
Output
Here, we can see that a TypeError was raised, since Python didn't know how to add
two Point objects together.
However, we can achieve this task in Python through operator overloading.
To overload operators their respective special methods should be implemented in the class.
To overload the + operator, we will need to implement __add__() function in the class. To
overload the - operator, we will need to implement __sub__() function in the class.
Consider that we have two objects which are a physical representation of a class (user-defined
data type) and we have to add two objects with binary ‘+’ operator it throws an error, because
compiler don’t know how to add two objects. So we define a method for an operator and that
process is called operator overloading. We can overload all existing operators but we can’t
create a new operator. To perform operator overloading, Python provides some special
function or magic function that is automatically invoked when it is associated with that
particular operator. For example, when we use + operator, the magic method __add__ is
automatically invoked in which the operation for + operator is defined.
Assignment Operators :
-= __ISUB__(SELF, OTHER)
+= __IADD__(SELF, OTHER)
*= __IMUL__(SELF, OTHER)
/= __IDIV__(SELF, OTHER)
%= __IMOD__(SELF, OTHER)
|= __IOR__(SELF, OTHER)
^= __IXOR__(SELF, OTHER)
Unary Operators :
– __NEG__(SELF, OTHER)
+ __POS__(SELF, OTHER)
~ __INVERT__(SELF, OTHER)
class A:
def __init__(self, a):
self.a = a
def __lt__(self, other):
if(self.a<other.a):
return "ob1 is lessthan ob2"
else:
return "ob2 is less than ob1"
def __eq__(self, other):
if(self.a == other.a):
return "Both are equal"
else:
return "Not equal"
ob1 = A(2)
ob2 = A(3)
print(ob1 < ob2)
ob3 = A(4)
ob4 = A(4)
print(ob1 == ob2)
output:
Not equal
Overriding:
Polymorphism in python defines methods in the child class that have the same name as the
methods in the parent class. In inheritance, the child class inherits the methods from the
parent class. Also, it is possible to modify a method in a child class that it has inherited
from the parent class.
This is mostly used in cases where the method inherited from the parent class doesn’t fit
the child class. This process of re-implementing a method in the child class is known
as Method Overriding. Here is an example that shows polymorphism with inheritance:
class Bird:
def intro(self):
def flight(self):
class parrot(Bird):
def flight(self):
class penguin(Bird):
def flight(self):
obj_bird = Bird()
obj_parr = parrot()
obj_peng = penguin()
obj_bird.intro()
obj_bird.flight()
obj_parr.intro()
obj_parr.flight()
obj_peng.intro()
obj_peng.flight()
Output:
Python’s memory allocation and deallocation method is automatic. The user does not have
to preallocate or deallocate memory similar to using dynamic memory allocation in
languages such as C or C++.
Python uses two strategies for memory allocation:
1. Reference counting
2. Garbage collection
the Python interpreter only used reference counting for memory management. Reference
counting works by counting the number of times an object is referenced by other objects in
the system. When references to an object are removed, the reference count for an object is
decremented. When the reference count becomes zero, the object is deallocated. Ex-
filter_none
# Literal 9 is an object
b=9
A reference cycle is created when there is no way the reference count of the object can reach.
Reference cycles involving lists, tuples, instances, classes, dictionaries, and functions are
common. The easiest way to create a reference cycle is to create an object which refers to
itself as in the example below:
def create_cycle():
# create a list x
x=[]
create_cycle()
Because create_cycle() creates an object x which refers to itself, the object x will not
automatically be freed when the function returns. This will cause the memory that x is using
to be held onto until the Python garbage collector is invoked.
Because reference cycles take computational work to discover, garbage collection must be a
scheduled activity. Python schedules garbage collection based upon a threshold of object
allocations and object deallocations. When the number of allocations minus the number of
deallocations is greater than the threshold number, the garbage collector is run. One can
inspect the threshold for new objects (objects in Python known as generation 0 objects) by
importing the gc module and asking for garbage collection thresholds:
# loading gc
import gc
# Importing gc module
import gc
edit
play_arrow
brightness_4
import gc
i=0
collected = gc.collect()
Creating cycles...
{1: {...}}
{2: {...}}
{3: {...}}
{4: {...}}
{5: {...}}
{6: {...}}
{7: {...}}
{8: {...}}
{9: {...}}
{10: {...}}
There are two ways for performing manual garbage collection: time-based and event-based
garbage collection.
Time-based garbage collection is simple: the garbage collector is called after a fixed time
interval.
Event-based garbage collection calls the garbage collector on event occurrence. For
example, when a user exits the application or when the application enters into idle state.
gc.enable()Enable automatic garbage collection.
Python Exceptions
Whenever an exception occurs, the program stops the execution, and thus the further code is
not executed. Therefore, an exception is the run-time errors that are unable to handle a Python
script. An exception is a Python object that represents an error.
The cause of an exception is often external to the program itself. For example, an incorrect
input, a malfunctioning IO device etc. Because the program abruptly terminates on
encountering an exception, it may cause damage to system resources, such as files. Hence,
the exceptions should be properly handled so that an abrupt termination of the program is
prevented. Exceptions are raised when the program is syntactically correct but the code resulted
in an error.
Python provides a way to handle the exception so that the code can be executed without any
interruption. If we do not handle the exception, the interpreter doesn't execute all the code that
exists after the exception.
>>> print( 0 / 0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
This time, you ran into an exception error. This type of error occurs whenever syntactically
correct Python code results in an error. The last line of the message indicated what type of
exception error you ran into.
Instead of showing the message exception error, Python details what type of exception error
was encountered. In this case, it was a ZeroDivisionError. Python comes with various built-in
exceptions as well as the possibility to create self-defined exceptions.
Example:
Common Exceptions
Python provides the number of built-in exceptions, but here we are describing the common
standard exceptions. A list of common exceptions that can be thrown from a standard Python
program is given below.
Exception hierarchy
1
Exception
2
StopIteration
Raised when the next() method of an iterator does not point to any object.
3
SystemExit
Base class for all built-in exceptions except StopIteration and SystemExit.
5
ArithmeticError
Base class for all errors that occur for numeric calculation.
6
OverflowError
7
FloatingPointError
8
ZeroDivisionError
Raised when division or modulo by zero takes place for all numeric types.
9
AssertionError
10
AttributeError
11
EOFError
Raised when there is no input from either the raw_input() or input() function and
the end of file is reached.
12
ImportError
13
KeyboardInterrupt
Raised when the user interrupts program execution, usually by pressing Ctrl+c.
14
LookupError
15
IndexError
16
KeyError
17
NameError
18
UnboundLocalError
Raised when trying to access a local variable in a function or method but no value
has been assigned to it.
19
EnvironmentError
Base class for all exceptions that occur outside the Python environment.
20
IOError
Raised when an input/ output operation fails, such as the print statement or the
open() function when trying to open a file that does not exist.
21
IOError
22
SyntaxError
23
IndentationError
Raised when indentation is not specified properly.
24
SystemError
Raised when the interpreter finds an internal problem, but when this error is
encountered the Python interpreter does not exit.
25
SystemExit
Raised when Python interpreter is quit by using the sys.exit() function. If not
handled in the code, causes the interpreter to exit.
26
TypeError
Raised when an operation or function is attempted that is invalid for the specified
data type.
27
ValueError
Raised when the built-in function for a data type has the valid type of arguments,
but the arguments have invalid values specified.
28
RuntimeError
Raised when a generated error does not fall into any category.
29
NotImplementedError
If the Python program contains suspicious code that may throw the exception, we must place
that code in the try block. The try block must be followed with the except statement, which
contains a block of code that will be executed if there is some exception in the try block.
The try: block contains one or more statements which are likely to encounter an exception.
If the statements in this block are executed without an exception, the subsequent except:
block is skipped.
If the exception does occur, the program flow is transferred to the except: block. The
statements in the except: block are meant to handle the cause of the exception appropriately.
For example, returning an appropriate error message.
You can mention a specific type of exception in front of the except keyword. The subsequent
block will be executed only if the specified exception occurs. There may be multiple except
clauses with different exception types in a single try block. If the type of exception doesn't
match any of the except blocks, it will remain unhandled and the program will terminate.
The rest of the statements after the except block will continue to be executed, regardless if
the exception is encountered or not.
You can mention a specific type of exception in front of the except keyword. The
subsequent block will be executed only if the specified exception occurs. There may be
multiple except clauses with different exception types in a single try block. If the type of
exception doesn't match any of the except blocks, it will remain unhandled and the program
will terminate.
Syntax
try:
#block of code
except Exception1:
#block of code
except Exception2:
#block of code
#other code
Example 1
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
except:
print("Can't divide with zero")
Output:
Enter a:10
Enter b:0
Can't divide with zero
We can also use the else statement with the try-except statement in which, we can place the
code which will be executed in the scenario if no exception occurs in the try block.
The syntax to use the else statement with the try-except statement is given below.
try:
#block of code
except Exception1:
#block of code
else:
#this code executes if no except block is executed
In Python, keywords else and finally can also be used along with the try and except clauses.
While the except block is executed if the exception occurs inside the try block, the else
block gets processed if the try block is found to be exception free.
Example 2
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
# Using Exception with except statement. If we print(Exception) it will return exception c
lass
except Exception:
print("can't divide by zero")
print(Exception)
else:
print("Hi I am else block")
Output:
Enter a:10
Enter b:0
can't divide by zero
<class 'Exception'>
The except statement with no exception
Python provides the flexibility not to specify the name of exception with the exception
statement.
Example
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
except:
print("can't divide by zero")
else:
print("Hi I am else block")
The except statement using with exception variable
We can use the exception variable with the except statement. It is used by using
the as keyword. this object will return the cause of the exception. Consider the following
example:
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
# Using exception object with the except statement
except Exception as e:
print("can't divide by zero")
print(e)
else:
print("Hi I am else block")
Output:
Enter a:10
Enter b:0
can't divide by zero
division by zero
Python facilitates us to not specify the exception with the except statement.
We can declare multiple exceptions in the except statement since the try block may
contain the statements which throw the different type of exceptions.
We can also specify an else block along with the try-except statement, which will be
executed if no exception is raised in the try block.
The statements that don't throw the exception should be placed inside the else block.
Example
try:
#this will throw an exception if the file doesn't exist.
fileptr = open("file.txt","r")
except IOError:
print("File not found")
else:
print("The file opened successfully")
fileptr.close()
Output:
The Python allows us to declare the multiple exceptions with the except clause. Declaring
multiple exceptions is useful in the cases where a try block throws multiple exceptions. The
syntax is given below.
Syntax
try:
#block of code
else:
#block of code
try:
a=10/0;
except(ArithmeticError, IOError):
print("Arithmetic Exception")
else:
print("Successfully Done")
Output:
Arithmetic Exception
The try...finally block
Python provides the optional finally statement, which is used with the try statement. It is
executed no matter what exception occurs and used to release the external resource. The finally
block provides a guarantee of the execution.
We can use the finally block with the try block in which we can pace the necessary code, which
must be executed before the try statement throws an exception.
Syntax
try:
# block of code
# this may throw an exception
finally:
# block of code
# this will always be executed
The finally block consists of statements which should be processed regardless of an
exception occurring in the try block or not. As a consequence, the error-free try block skips
the except clause and enters the finally block before going on to execute the rest of the
code. If, however, there's an exception in the try block, the appropriate except block will
be processed, and the statements in the finally block will be processed before proceeding
to the rest of the code.
Raising exceptions
An exception can be raised forcefully by using the raise clause in Python. It is useful in in that
scenario where we need to raise an exception to stop the execution of the program.
For example, there is a program that requires 2GB memory for execution, and if the program
tries to occupy 2GB of memory, then we can raise an exception to stop the execution of the
program.
Syntax
1. raise Exception_class,<value>
To raise an exception, the raise statement is used. The exception class name follows it.
An exception can be provided with a value that can be given in the parenthesis.
To access the value "as" keyword is used. exception variable is used sed as a reference variable
which stores the value of the exception.
Example
try:
age = int(input("Enter the age:"))
if(age<18):
raise ValueError
else:
print("the age is valid")
except ValueError:
print("The age is not valid")
Output:
try:
num = int(input("Enter a positive integer: "))
if(num <= 0):
# we can pass the message in the raise statement
raise ValueError("That is a negative number!")
except ValueError as e:
print(e)
Output:
Example 3
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
if b is 0:
raise ArithmeticError
else:
print("a/b = ",a/b)
except ArithmeticError:
print("The value of b can't be 0")
Output:
Enter a:10
Enter b:0
The value of b can't be 0
Programmers may name their own exceptions by creating a new exception class. Exceptions need
to be derived from the Exception class, either directly or indirectly. Although not mandatory,
most of the exceptions are named as names that end in “Error” similar to naming of the standard
exceptions in python.
Steps in User defined Exception:
1. Create Custom Exception Class
class MyException(Exception):
def __init__(self, arg):
self.msg = arg
2. Raise the exception
raise MyException(‘message’)
3. Handle the custom exception thrown
try:
code
except MyException as me:
print( me )
For example:
Assertions:
Assertions in any programming language are the debugging tools which help in smooth flow of
code. Assertions are mainly assumptions that a programmer knows always wants to be true and
hence puts them in code so that failure of them doesn’t allow the code to execute further. This
has a much greater utility in testing and Quality assurance role in any development domain.
Different types of assertions are used depending upon the application.
An assertion is a sanity-check that you can turn on or turn off when you are done with your
testing of the program.
The easiest way to think of an assertion is to liken it to a raise-if statement (or to be more
accurate, a raise-if-not statement). An expression is tested, and if the result comes up false, an
exception is raised.
Programmers often place assertions at the start of a function to check for valid input, and after
a function call to check for valid output.
In python assert keyword helps in achieving this task. This statement simply takes input a
boolean condition, which when returns true doesn’t return anything, but if it is computed to be
false, then it raises an AssertionError along with the optional message provided.
Web scraping is the process of gathering information from the Internet. Even copy-pasting the
lyrics of your favorite song is a form of web scraping! However, the words “web scraping”
usually refer to a process that involves automation. Web scraping is an automated method used
to extract large amounts of data from websites. The data on the websites are unstructured. Web
scraping helps collect these unstructured data and store it in a structured form. There are
different ways to scrape websites such as online Services, APIs or writing your own code.
One challenge is variety. Every website is different. While you’ll encounter general structures
that tend to repeat themselves, each website is unique and will need its own personal treatment
if you want to extract the information that’s relevant to you.
Another challenge is durability. Websites constantly change. Say you’ve built a shiny new
web scraper that automatically cherry-picks precisely what you want from your resource of
interest. The first time you run your script, it works flawlessly. But when you run the same
script only a short while later, you run into a discouraging and lengthy stack of tracebacks!
Price Comparison: Services such as ParseHub use web scraping to collect data from
online shopping websites and use it to compare the prices of products.
Email address gathering: Many companies that use email as a medium for marketing,
use web scraping to collect email ID and then send bulk emails.
Social Media Scraping: Web scraping is used to collect data from Social Media
websites such as Twitter to find out what’s trending.
Research and Development: Web scraping is used to collect a large set of data
(Statistics, General Information, Temperature, etc.) from websites, which are analyzed
and used to carry out Surveys or for R&D.
Job listings: Details regarding job openings, interviews are collected from different
websites and then listed in one place so that it is easily accessible to the user.
Ease of Use: Python is simple to code. You do not have to add semi-colons “;” or curly-
braces “{}” anywhere. This makes it less messy and easy to use.
Large Collection of Libraries: Python has a huge collection of libraries such
as Numpy, Matlplotlib, Pandas etc., which provides methods and services for various
purposes. Hence, it is suitable for web scraping and for further manipulation of
extracted data.
Dynamically typed: In Python, you don’t have to define datatypes for variables, you
can directly use the variables wherever required. This saves time and makes your job
faster.
Easily Understandable Syntax: Python syntax is easily understandable mainly
because reading a Python code is very similar to reading a statement in English. It is
expressive and easily readable, and the indentation used in Python also helps the user
to differentiate between different scope/blocks in the code.
Small code, large task: Web scraping is used to save time. But what’s the use if you
spend more time writing the code? Well, you don’t have to. In Python, you can write
small codes to do large tasks. Hence, you save time even while writing the code.
Community: What if you get stuck while writing the code? You don’t have to worry.
Python community has one of the biggest and most active communities, where you can
seek help from.
To extract data using web scraping with python, you need to follow these basic steps:
Now let us see how to extract data from the Flipkart website using Python.
BeautifulSoup: Beautiful Soup is a Python package for parsing HTML and XML documents.
It creates parse trees that is helpful to extract the data easily.
Pandas: Pandas is a library used for data manipulation and analysis. It is used to extract the
data and store it in the desired format.
The requests library:The first thing we’ll need to do to scrape a web page is to download the
page. We can download pages using the Python requests library. The requests library will make
a GET request to a web server, which will download the HTML contents of a given web page
for us. There are several different types of requests we can make using requests, of
which GET is just one.
After running our request, we get a Response object. This object has status_code property,
which indicates if the page was downloaded successfully: A status_code of 200 means that the
page downloaded successfully.
We can use the BeautifulSoup library to parse this document, and extract the text from the p
tag. We first have to import the library, and create an instance of the BeautifulSoup class to
parse our document:
from bs4 import BeautifulSoup
As all the tags are nested, we can move through the structure one level at a time. We can first
select all the elements at the top level of the page using the children property of soup. Note that
children returns a list generator, so we need to call the list function on it: list(soup.children)
Installing PyPDF2 can be done with pip or conda if you happen to be using Anaconda instead
of regular Python.
• Getting Sheet List and Name sheet_list = wb.sheetnames print("SHEET LIST = ",sheet_list)
sheet = wb['ISE_A’] print("SHEET = ",sheet)