Professional Documents
Culture Documents
Core Python, Advanced Python & Django Framework
Core Python, Advanced Python & Django Framework
Core Python,
Advanced Python
&
Django
Framework
Core Python
Syllabus –
1. Language fundamentals
2. Operators
3. Input and Output statements
4. Flow Control
5. Strings
6. List Data Structure
7. Tuple Data Structure
8. Set Data Structure
9. Dictionary Data Structure
10. Functions
11. Modules
12. Packages
Advanced Python
Syllabus –
1. OOP’s
2. Exception Handling
3. File Handling
4. Multi-Threading
5. Regular Expressions
6. Web Scrapping
7. Python Data base Connectivity(PDBC)
8. Decorators
9. Generators
10. Logging Module
11. Assertions
12. Introduction to Web Application Development with DJango
CHAPTER
1
INTRODUCTION
Syllabus:
Introduction: History of Python, Need of Python Programming, Applications Basics
of Python Programming Using the REPL(Shell), Running Pythod Scripts, Variables,
Assignment, Keywords, Input-Output, Indentation
Python History:
Python is an object-oriented, high level language, interpreted, dynamic and
multipurpose programming language.
Python is easy to learn and powerful scripting language which makes it
attractive for Application Development.
Python supports multiple programming pattern, including object-oriented
programming, imperative and functional programming or procedural styles.
Python makes the development and debugging fast because there is no
compilation step included in python development and edit-test-debug cycle is
very fast.
Python is Interpreted: Python is processed at runtime by the interpreter. You do
not need to compile your program before executing it. This is similar to PERL and
PHP.
Python is Interactive: You can actually sit at a Python prompt and interact with
the interpreter directly to write your programs.
Python is Object-Oriented: Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
o The design began in the late 1980s and was first released in February 1991.
o The implementation of Python was started in the December 1989 by Guido
Van Rossum at the National Research Institute for Mathematics and
Computer Science in the Netherland.
o Python is derived from many other languages, including ABC, Modula-3, C,
C++, Algol-68, SmallTalk, Unix shell, and other scripting languages.
o Python is copyrighted. Like Perl, Python source code is now available under
the GNU General Public License (GPL).
o Why Python was created?
o In late 1980s, Guido Van Rossum was working on the Amoeba distributed
operating system group. He wanted to use an interpreted language like ABC
(ABC has simple easy-to-understand syntax) that could access the Amoeba
system calls. So, he decided to create a language that was extensible. This led
to a design of new language which was later named Python.
Python Applications
1) Console Based Application
Python can be used to develop console based applications. For example: IPython.
Limitations of Python:
1. Not suitable for Enterprise application
2. Not suitable for mobile applications
3. Performacne wise not up to the mark
User of Python:
Youtube,Dropbox, Yahoo, google,Zope Corporation, Ultraseek,Shopzilla,yum
Youtube is orginally written in Python and mysql.
Dropbox web-based file hosting service is implemented using Python.
Both the Dropbox server(running in the cloud) and desktop client software are
primarily written in Python.
Yahoo Maps uses Python.
Many components of the Google spider and search engine are written in Python.
Python is now used in the Google search engine, in mission-critical projects at
NASA, and in transaction processing at the New York Stock Exchange. NASA,
Stock Exchange, NST(National Security)
2. Having downloaded the Python distribution now execute it. Double click on the
downloaded software. Follow the steps for installation:
Click the Finish button and Python will be installed on your system.
8. Click on Ok button:
9. Click on Ok button:
Press Enter key and the Command Prompt will appear like:
Eg:
2) Script Mode:
Using Script Mode , you can write your Python code in a separate file using any
editor of your Operating System.
Execute your Python code on the Python prompt and it will display result
simultaneously.
☛ You now first need to create environments to run Python. Go ahead and execute
the following commands.
$ mkdir environments
$ cd environments
$ python3 -m venv test_env
☛ Before you can use the <test_env>, you have to activate it first. The following
command will do the activation for you.
$ source test_env/bin/activate
Your prompt will now a little different than the standard one.
(test_env) techbeamers@techbeamers:~/environments$
This prefix indicates that the environment test_env is currently active. And you can
create programs to use the environment’s settings and packages.
☛ We have our virtual env set up, let’s write a simple “Hello, World!” script. To do
this, open up a command-line text editor such as vi and create a new file.
The vi editor will open the text file in the terminal. Write the code given below. Press
“:wq” to save and exit from the editor.
print("Hello, World!")
☛ Once you exit out of vi and return to the shell, let’s run the script.
# Output
Hello, World!
To log out of the environment, type the command “deactivate,” and it’ll return to
your original directory.
Python Variables
Variable is a name of the memory location where data is stored. Once a variable is
stored that means a space is allocated in memory.
Assigning values to Variable:
We need not to declare explicitly variable in Python. When we assign any value to
the variable that variable is declared automatically.
The assignment is done using the equal (=) operator.
Multiple Assignment:
Multiple assignment can be done in Python at a time.
There are two ways to assign values in Python:
1. Assigning single value to multiple variables:
Eg:
x=y=z=50
print x
print y
print z
Output:
>>>
50
50
50
>>>
2.Assigning multiple values to multiple variables:
Eg:
a,b,c=5,10,15
print a
print b
Python Comments
In Python there are basically two ways to comment:
single line and multiple line.
Single line commenting is good for a short, quick comment (or for debugging) #
Multiple line comments are slightly different. Simply use 3 single quotes before and
after the part you want commented.
Multiplie Line ''' data
'''
input() function: The input() function is used to accept an input from a user. A
programmer can ask a user to input a value by making use of input()
variable name =input()
or
variable name=input(‘String’)
eval() function: The full form of eval function is to evaluate. It takes a string as
parameter and returns it as if it is a Python expression. For example, if we try to
run the statement eval(‘print(“Hello”)’) in Python interactive mode, it will actually
run the statement print(“Hello”).
eval(‘print(“Hello”)’)
Hello
The eval function takes a string and returns it in the type it is expected.
X=eval(‘123’)
123
Input-Output Statements:
Ex:
# Store input numbers:
a1 = input('Enter first number: ')
a2 = input('Enter second number: ')
Ex:
a,b,c=10,20,30
print('a={},b={},c={}'.format(a,b,c))
print('a={2},b={0},c={1}'.format(a,b,c))
print('a={x},b={y},c={z}'.format(y=b,z=c,x=a))
Indentation:
Leading whitespace (spaces and tabs) at the beginning of locial line is used to
compute the identation leve lf the line, which in turn is used to determine the
grouping of statements.
CHAPTER
2
TYPES, OPERATORS
AND EXPRESSIONS
Data Types:
Core Datatypes
int bytes
float bytearray
complex range
bool list
str tuple
Types or Literals:
Literals can be defined as a data that is given in a variable or constant.
Python support the following literals:
Numeric Literals
String Literals
Boolean Literals
special literals
Numeric Literals: -
Numeric Literals are immutable. Numeric literals can belong to following four
different numerical types.
Boolean literals:
A Boolean literal can have any of the two values: True or False.
Special literals.
Python contains one special literal i.e., None.
None is used to specify to that field that is not created. It is also used for end of lists
in Python.
Eg:
val1=10
val2=None
val1
10
val2
print val2
None
bytes: A group of byte values
x=[10,20,30,40]
b=bytes(x)
The only allowed values are 0 to 255. It is immutable
bytearray: It can be used to represent binary information like images, video files,
audio files etc. It is exactly same as bytes. It is mutable
Type Casting or Type Coersion
int() : The int function converts a string or a number into whole number to integer.
The int function removes everything after the decimal point.
int(124.456) => 124
int(‘123’) => 123
float() : The float function converts a string into a floating point number
float(’10.23’) => 10.23
complex() : A complex number is number that can be expressed in the form a+bj
complex(10) => 10+0j
complex(10.5) => 10.5 + 0j
complex(true) => 1+0j
complex(false) => 0j
complex(‘10’) => 10+0j
complex(“ten”) => valueerror
complex(10,20) => 10+20j
Built-in Functions:
Built-n Functions are the functions which are built into(already available) Python
and can be accessed by end-users.
sorted() file()
abs() input()
all() int()
any() len()
basestring() open()
bin() raw_input()
boo()
enumerate()
eval()
print() -> print value of object
type() -> print type of object
id() -> print address of object
Every thing is an object in python
Python Operators
Operators are particular symbols which operate on some values and produce an
output.The values are known as Operands.
Eg:
4+5=9
Here 4 and 5 are Operands and (+) , (=) signs are the operators. They produce the
output 9.
Python supports the following operators:
1. Arithmetic Operators. +, -, *, /, %, //, **
2. Relational Operators. <,<=,>,>=,==,!=
3. Assignment Operators and compound operators =,+=, -= ,*=, /=, %=
4. Logical Operators. and, or and not
5. Membership Operators. in, not in
6. Identity Operators. is, not is
7. Bitwise Operators. ~, &, |, ^, <<, >>
Arithmetic Operators:
Operators Description Example Output
= Assignment
and Logical AND(When both conditions are true output will be true)
is not Returns true if identity of two operands are not same, else
false.
Example:
a=20
b=20
if( a is b):
print ?a,b have same identity?
else:
print ?a, b are different?
b=10
if( a is not b):
print ?a,b have different identity?
else:
print ?a,b have same identity?
Bit-wise operators: Bit-wise operators are used to manipulate the data at bit level.
It operates on integers only. It may not be applied to float. Bit-wise operators are
Operator Name
~ One’s complement
& Bitwise AND
| Bitwise Inclusive OR
^ Bitwise Exclusive OR
<< Left shift
>> Right shift
One’s complement(~): This operator performs negation operation on bits i.e.,
converting 0’s to 1’s and 1’s to 0’s
Ex: a=6 = 0000 0110
~a = = 1111 1001
Bitwise AND(&): This operator performs both operands bits 1’s it returns 1’s
otherwise 0’s
Ex: a=6 =0000 0110
b=7 =0000 0111
a&b =0000 0110
Bitwise Inclusive OR(|): This operator performs either one bit 1’s it returns 1’s
otherwise 0’s
Ex: a=6 =0000 0110
b=7 =0000 0111
a&b =0000 0111
Bitwise Exclusive OR(^): This operator performs all bits 1’s or 0’s it returns 0’s
otherwise 1’s.
Ex: a=6 =0000 0110
b=7 =0000 0111
a&b =0000 0001
Left Shift(<<): This operator performs the shift bits.
Ex: a=6 =0000 0110
a<<3 =0011 0000
Right Shift(>>): This operator performs the shift bits.
Ex: a=6 =0000 0110
a>>2 =0000 0001
Ternary Operator: -
Ex: max = a if a>b else b
min = a if a<b and a<c else b if b<c else c
Test
expression
False
True
Two-way selection statements are
1. Simple if statement
2. If…else statement
3. Nested if…else statement
4. Multi-way – if-elif-else statements
Python If Statements
The if statement in python is same as c language which is used test a condition. If
condition is true, statement of if block is executed otherwise it is skipped.
a=10
if a==10:
print "Bhuvana Kruthi"
Output:
Bhuvana Kruthi
Syntax:
if(condition):
Test
False
statements
expression
else:
statements
True
statements statements
Example-
year=2000
if year%4==0:
print "Year is Leap"
else:
print "Year is not Leap"
Output:
Year is Leap
Nested If…else Statement: When a series of if… else statements, if… else
statement within if… else statement called nested if.
Syntax: When we need to check for multiple conditions to be true then we use
elif Statement.
This statement is like executing a if statement inside a else statement.
Syntax:
If statement:
Body Test
elif statement: expression
Body
else:
Body
Example: statements
Test
a=10
if a>=20: expression
print "Condition is True"
statements statements
Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology
Python Programming 45
else:
if a>=15:
print "Checking second value"
else:
print "All Conditions are false"
Output:
All Conditions are false.
While Statement: - The while is an entry controlled loop statement. The test
condition is evaluated if the condition is true, then the body of the loop is executed.
After execution of the body, the test condition is once again evaluated and if it is
true, the body is executed once again. This process of repeated execution of the
body continues until the test condition finally becomes false and the control is
transferred out of the loop.
while Loop is used to execute number of statements or body till the condition
passed in while is true. Once the condition is false, the control will come out of the
loop.
Test
expression
False
True
statements
a=10
while a>0:
print "Value of a is",a
a=a-2
print "Loop is Completed"
Output:
Value of a is 10
Value of a is 8
Value of a is 6
Value of a is 4
Value of a is 2
Loop is Completed
Explanation:
Firstly, the value in the variable is initialized.
Secondly, the condition/expression in the while is evaluated. Consequently if
condition is true, the control enters in the body and executes all the statements .
If the condition/expression passed results in false then the control exists the
body and straight away control goes to next instruction after body of while.
Thirdly, in case condition was true having completed all the statements, the
variable is incremented or decremented. Having changed the value of variable
range() function(Slice operation): The range function has one, two or three
parameters. The last two parameters in range() are optional.
range(begin, end, step)
The ‘begin’ is the first beginning number in the sequence at which the list
starts.
The ‘end’ is the limit, ie. The last number in the sequence.
The ‘Step’ is the difference between each number in the sequence.
Note: range doest not support item assignment. floating point value not read
range(5) [0,1,2,3,4]
range(1,5) [1,2,3,4]
range(1,10,2) [1,3,5,7,9]
range(5,0,-1) [5,4,3,2,1]
range(5,0,-2) [5,3,1]
range(-4,4) [-4,-3,-2,-1,0,1,2,3]
range(-4,4,2) [-4,-2,0,2]
range(0,1) [0]
range(1,1) Empty
range(0) Empty
For Statement: - The for loop is another entry-controlled loop that performs an
initialization step and then evaluates a test condition. If the test condition evaluates
to true, a given statement is executed and an increment expression is evaluated
repeatedly as long as the condition continues to evaluate to true.
for Loop is used to iterate a variable over a sequence (i.e., list or string) in the
order that they appear.
Syntax :
for <variable> in <sequence>:
Program to display table of Number:
num=2
for a in range (1,6):
print num * a
Output:
2
4
6
8
10
Program to find sum of Natural numbers from 1 to 10.
sum=0
for n in range(1,11):
sum+=n
print sum
eg:
for i in [1,2,3,4,5]:
if i==4:
print "Element found"
break
print i,
Output:
>>>
1 2 3 Element found
>>>
Continue Statement
continue Statement is a jump statement that is used to skip the present iteration
and forces next iteration of loop to take place. It can be used in while as well as for
loop statements.
eg:
a=0
while a<=5:
a=a+1
if a%2==0:
continue
print a
print "End of Loop"
Output:
>>>
1
3
5
End of Loop
>>>
CHAPTER
3
DATA STRUCTURES
Syllabus:
Data Structures: Lists – Operations, Slicing, Methods; Tuples, Sets, Dictionaries,
Sequences, Comprehensions.
Python Collections (Arrays)
There are four collection data types in the Python programming language:
List is a collection which is ordered and changeable. Allows duplicate members.
1.2 Updating values in List: - Once created, one or more elements of a list can be
easily updated by giving the slice on the left-hand side of the assignment operator.
You can add to elements in a list with the append() method.
Eg:
cse = [10,11,13,15,16,29,24,14,12]
print ("list items are",cse)
cse[5]=100
print ("list after updation is :",cse)
cse.append(200)
print ("list after appending a value is :",cse)
output:
list items are [10, 11, 13, 15, 16, 29, 24, 14, 12]
list after updation is : [10, 11, 13, 15, 16, 100, 24, 14, 12]
list after appending a value is : [10, 11, 13, 15, 16, 100, 24, 14, 12, 200]
1.3 Deleting Elements from a List: - del statement can be used to delete an
element from the list. It can also be used to delete all items from startIndex to
endIndex.
Eg:
cse = [10,11,13,15,16,29,24,14,12]
print ("list items are",cse)
del cse[3]
print ("List after deleting element is ",cse)
del cse[2:5]
print ("List after deleting elements is ",cse)
del cse[:]
print ("List after deleting all elements is ",cse)
output:
list items are [10, 11, 13, 15, 16, 29, 24, 14, 12]
List after deleting element is [10, 11, 13, 16, 29, 24, 14, 12]
List after deleting elements is [10, 11, 24, 14, 12]
List after deleting all elements is []
1.4 Nested List: - Nested List means a list within another list. We have already said
that a list has elements of different data types which can include event a list.
Eg:
cse = [10,11,13,15,[4,5.6,7.8],16,29,24,14,12]
2. Tuple:
A tuple is a sequence of immutable objects. This means that while you can change
the value of one or more items in a list, you cannot change the values in a tuple.
The objects are enclosed within parenthesis and separated by comma.
Tuple is similar to list. Only the difference is that list is enclosed between square
bracket, tuple between parenthesis and List have mutable objects whereas Tuple
have immutable objects.
Syntax: Tuple variable = (val1,val2,val3,……) where values can be an integer,
a floating number, a character, or a string.
Tup1 = ( ) Output : ( ) Creates an empty tuple
Tup1 = (5) Output : (5) Creates a tuple with a single element
Tup1=(2,4,5,3) Output: (2,4,5,3) Creates a tuple of integers
Tup1=(‘a’,’b’,’c’,’d’) Output: (‘a’,’b’,’c’,’d’) Creates a tuple of characters
Tup1=(‘raj’,’kumar’,’ram’) Output: (‘raj’,’kumar’,’ram’)
2.2 Updating values in Tuple: - Elements of the Tuple cannot be updated. This is
due to the fact that Tuples are immutable. Whereas the Tuple can be used to form a
new Tuple.
data=(10,20,30)
data[0]=100
print data
Output:
(10, 20, 30, 40, 50, 60)
2.3 Deleting elements from Tuple: - Deleting individual element from a tuple is
not supported. However the whole of the tuple can be deleted using the del
statement.
Eg:
data=(10,20,'rahul',40.6,'z')
print (data)
del data[3]
del data #will delete the tuple data
print (data) #will show an error since tuple data is already deleted
Output:
(10, 20, 'rahul', 40.6, 'z')
Traceback (most recent call last):
File "C:/Users/Admin/AppData/Local/Programs/Python/Python36-
32/cse4.py", line 3, in <module>
del data[3]
TypeError: 'tuple' object doesn't support item deletion
2.4 Nested Tuple: - Python allows you to define a tuple inside another tuple. This
is called a Nested Tuple.
Eg:
cse = (10,11,13,15,(4,5.6,7.8),16,29,24,14,12)
print ("tuple items are",cse)
print ("sub tuple is",cse[4])
print ("sub tuple element is ",cse[4][2])
output:
tuple items are (10, 11, 13, 15, (4, 5.6, 7.8), 16, 29, 24, 14, 12)
sub tuple is (4, 5.6, 7.8)
sub tuple element is 7.8
2.5 Operations on Tuples:
Operation Description Example & Output
Len Gives the length of a Eg:
tuple cse = (10,11,13,15,16,29,24,14,12)
print ("tuple length =",len(cse))
3. Sets: - Sets is another data structure supported by Python. Basically, sets are
same as lists but with a difference that sets are lists with no duplicate entries.
Technically, a set is a mutable and an unordered collection of items. This mean that
we can easily add or remove items from it.
3.1 Creating a Set: - A set is created by placing all the elements inside curly
brackets { }, separated by comma or by using the built-in function set( ).
Set variable = {var1,var2,……}
Eg:
s={1,2.4,"abc",1}
print (s)
list1 = [1,2,4,5,6,5,4,3,2,1]
print(set(list1))
output:
{1, 'abc', 2.4}
{1, 2, 3, 4, 5, 6}
3.2 Set Operations:
Operation Description Example & Output
s.update(t) adds elements of set t in the set s Eg:
provided that all duplicates are s=set([1,2,3,4,5])
avoided t=set([6,7,8])
s.update(t)
print(s)
output:
{1, 2, 3, 4, 5, 6, 7, 8}
s.add(x) Adds element x to the set s Eg:
provided that all duplicates are s=set([1,2,3,4,5])
avoided s.add(6)
print(s)
output:
{1, 2, 3, 4, 5, 6}
s.remove(x) Removes element x from set s. Eg:
Return keyError if x is not s=set([1,2,3,4,5])
present s.remove(3)
print(s)
output:
{1, 2, 4, 5}
4. Dictionaries: -
Dictionary is a data structure in which we store values as a pair of key and value.
Each key is separated from its value by a colon(:) and consecutive items are
separated by commas. The entire items in a dictionary are enclosed in curly
bracket({ }).
4.1 Creating a Dictionary: -
To create an empty dictionary, just write the following line of code.
d={}
print(d)
A dictionary can be also created by specified key-value pairs separated by a
colon in curly brackets as shown below.
Syntax: dictionary-name = {key_1:value_1,
key_2:value_2,
key_3:value_3,
…}
Dictionary keys are case-senstive.The pair i.e., key and value is known as
item.
Eg:
data={100:'Ravi' ,101:'Vijay' ,102:'Rahul'}
print (data)
output:
{100: 'Ravi', 101: 'Vijay', 102: 'Rahul'}
Note: -Dictionary is mutable i.e., value can be updated. Key must be unique and
immutable. Value is accessed by key. Value can be updated while key cannot be
changed.
Dictionary is known as Associative array since the Key works as Index and they are
decided by the user.
Eg:
cse={}
cse[1]='Ravi'
cse[2]='Manoj'
cse['name']='Hari'
cse[4]='Om'
print (cse[2])
print (cse['name'])
print (cse[1])
print (cse)
output:
Manoj
Hari
Ravi
{1: 'Ravi', 2: 'Manoj', 'name': 'Hari', 4: 'Om'}
CHAPTER
4
Syllabus:
Functions - Defining Functions, Calling Functions, Passing Arguments, Keyword
Arguments, Default Arguments, Variable-length arguments, Anonymous Functions,
Fruitful Functions(Function Returning Values), Scope of the Variables in a Function
- Global and Local Variables.
Modules: Creating modules, import statement, from. Import statement, name
spacing
Display()
n=int(input("enter n value"))
add(n)
Parameter with Default Values: Parameters within a function’s definition can have
default values. We can provide default value to a parameter by using assignment(=)
operator.
Ex:
def display(name,msg="Welcome to Python"):
print("Hello",name,msg)
display("Ramesh")
Ex: Write a program to calculate the area of a circle using the formula
Area=pi*(r)2
def area_circle(pi=3.14,radius=1):
area=pi*radius*radius
print("radius =",radius)
print("the area of Circle =",area)
area_circle()
area_circle(radius=5)
Ex:
def disp_values(a,b=10,c=20):
print("a= ",a," b= ",b,"c= ",c)
disp_values(15)
disp_values(50,b=30)
disp_values(c=80,a=25,b=35)
The Local and Global Scope of a Variable: variables and parameters that are
initialized within a function including parapeters, are said to exist in that function’s
local scope. Variables that exist in local scope are called local variables. Variables
that are assigned outside functions are said to exist in global scope. Thefore,
variables that exist in global scope are called global variables.
Ex:
p=20 #global variable p
Note: Accessing a local variable outside the scope will cause an error
The return statement: The return statement is used to return value from the
function. It is lso used to return from a function, i.e., break out of the function.
Returning multiple values: It is possible to return multiple values in Python.
Assign returned multiple values to variable: - It is also possible for a function to
perform certain operations, return multiple values and assign the returned multiple
values to multiple variable.
def compute(n):
print("number =",n)
return (n*n,n*n*n)
square,cube=compute(4)
print("Square =",square,"Cube =",cube)
output:
number = 4
Square = 16 Cube = 64
n=int(input("enter n value"))
print("factorial value=",fact(n))
output:
enter n value5
factorial value= 120
Ex: Write a recursive function which computes the nth Fibnacci numbers are
defined as
Fib(0) = 1
Fib(1) = 1
Fib(n) = fib(n-1)+fib(n-2)
Write this as a python code and then find the 8th Fibonacci number
def fib(n):
if n==0 :
return 1
if n==1 :
return 1
return fib(n-1)+fib(n-2)
print("The value of 8th Fib number =",fib(8))
output:
The value of 8th Fib number = 34
Lambda Function: - These are also known as anonymous functions. Such kind of
functions are not bound to a name. They only have a code to execute that which is
associated with them.
A lambda function can take any number of arguments, but can only have one
expression.
The basic syntax for a lambda function is:
Name = lambda(variable):Code
lambda arguments : expression
Ex: without lambda function
def funct(x):
return x*x*x
print(funct(3))
Ex: with lambda function
cube=lambda x:x*x*x
print(cube(2))
Note: a) A lambda function does not contain a return statement
b) It contains a single expression as a body and not a block of statements as a
body.
Modules: Modules contain definitions of functions, classes and variables which can
be utilized in other programs.
Some python modules are written in languages other than Python, most commonly
C or C++. Such a module is called an Extension Module.
Writing a module is like writing a simple python program in a file and saving
it in .py extension.
temp.py
def display(name):
print("Hello ",name," Welcome to python world")
Use a Module
The python import keyword lets you to include other modules in your program.
Now we can use the module we just created, by using the import statement:
main.py
import temp
temp.display("Ramesh")
output:
Hello Ramesh Welcome to python world
Note: The module which we have imported and the file, in which we have used the
import statement, should be in the same dictory.
The module can contain functions, as already described, but also variables of all
types (arrays, dictionaries, objects etc):
temp.py
person1 = {
"name": "Ramesh",
"age": 36,
"country": "India"
}
main.py
import temp
Built-in Modules
There are several built-in modules in Python, which you can import whenever you
like.
import platform
x = platform.system()
print(x)
Using the dir() Function
There is a built-in function to list all the function names (or variable names) in a
module. The dir() function:
import platform
x = dir(platform)
print(x)
Note: The dir() function can be used on all modules, also the ones you create
yourself.
person1 = {
"name": "Ramesh",
"age": 36,
"country": "India"
}
main.py
from temp import person1
print (person1["age"])
Note: When importing using the from keyword, do not use the module name when
referring to elements in the module.
Example: person1["age"], not temp.person1["age"]
Packages: -
A package is a collection of related modules stored in a directory or subdirectories.
Creating Package:
Ex:
Temp
__init__.py
a.py
b.py
step1: Let us create a package(folder). The name of the package, say “temp”.
step2: Create __init__.py file inside the created package, viz “temp”. The directory
should contain a file named __init__.py. This file can be empty or it may contain
valid python code. Let keep it as empty file.
step3: Inside the package, let us create two different .py files, i.e. a.py and b.py.
step4: write python code inside a.py and b.py files. Thus, the contents of a.py and
b.py files are as follows.
#a.py
def display1():
print("Hello Ramesh")
def display2():
print("Hello Suresh")
#b.py
def display3():
print("Hello ashok")
#main.py
from temp import a,b
a.display1()
a.display2()
b.display3()
What is PIP?
PIP is a package manager for Python packages, or modules if you like.
Note: If you have Python version 3.4 or later, PIP is included by default.
Check if PIP is Installed
C:\Users\YRamesh>pip --version
pip 10.0.1 from c:\python37\lib\site-packages\pip (python 3.7)
C:\Users\YRamesh>pip list
Package Version
--------------------- -------
Django 2.1.3
pip 10.0.1
pytz 2018.7
setuptools 39.0.1
virtualenv 16.1.0
virtualenvwrapper-win 1.2.5
You are using pip version 10.0.1, however version 18.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip'
command.
CHAPTER
5
OOP’s in Python
Error and Exceptions
Syllabus:
OOPs in Python: Classes, ‘self variable’, Methods, Constructor Method,
Inheritance, Overriding Methods, Data hiding
Error and Exceptions: Difference between an error and Exception, Handling
Exception, try except block, Raising Exceptions, User Defined Exceptions
OOP’s Concepts:
The OOP’s (Object Oriented Programming System) Concepts are
1. Class
2. Object
3. Data Abstraction
4. Data Encapsulation
5. Inheritance
6. Polymorphism
Class: A Class is user defined data type it contains data and functions. The data is
called member data and functions are called member functions or methods.
Syntax : class classname:
Intilization
attributes
methods()
-------
Statementn
In Python, a class is defined by using a keyword class like a function definition
begins with the keyword def.
Object: It is instance of class. Object is an entity that has state and behavior.
Dot Operator:
The dot Operator(.) is used to access the instance variables and methods of class
objects.
Stud1.getdata( );
Stud1.name
It is also used to access classes and sub-packages from a package.
Data Abstraction: - Accessing the Data. The Access specifiers are private and
public
Data Encapsulation: - Wrapping up of data into single unit is called Data
Encapsulation.
Ex: Class
It is used to restrict access to methods and variables. In encapsulation, code
and data are wrapped together within a single unit from being modified by accident.
Inheritance: - It means acquire the properties of existing class. Main class is called
Base class, sub class class is called Derived class.
It specifies that one object acquires all the properties and behaviors of parent
object. By using inheritance, you can define a new class with a little or no changes
to the existing class. The new class is known as derived class or child class and
from which it inherits the properties is called base class or parent class.
It provides re-usability of the code.
Polymorphism: - Polymorphism is made by two words "poly" and "morphs". Poly
means many and Morphs means form, shape. It defines that one task can be
performed in different ways.
Creating Objects: Once a class is defined, the next job is to crate an object(or
instance) of that class. The object can then access class variables and class
methods using the dot operator(.).
objectname=classname()
Creating an object or instance of a class known as class instantiaton.
Ex:
class avanthi:
x=10
t1=avanthi()
print(t1.x)
output: 10
Note: Functions defined inside a class are called class methods.
Self Variable:
self is a reference variable which is alway pointing to current object. Within the
python class to refer current object we should use self variable
class Student:
Class Method and ‘self’ Argument: - Class methods(or functions defined in the
class) are exactly same as ordinary functions that we have been defining so far with
just one small difference. Class methods must have the first argument named as
self . This is the first argument that is added to the beginning of the parameter list.
You do not pass a value for this parameter when you call the method. Python
provides its value automatically. The self argument refers to the object itself. That
is, the object that has called the method. This means that even if a method that
takes no arguments, it should be defined to accept the self.
Ex:
class avanthi:
x=10
def display(self):
print("value=",self.x)
t1=avanthi()
t1.display()
output: value= 10
Ex: parameterized class method
class avanthi:
x=10
def display(self,k):
self.x=k
print("value=",self.x)
t1=avanthi()
t1.display(25)
output: value=25
Note: The statement inside the class definition must be properly indented.
Class methods or functions that begins with double underscore(__) are
special functions with a predefined and special meaning.
t1=avanthi()
t1.display()
class avanthi:
def __init__(self,k):
self.x=k
def display(self):
print("value=",self.x)
t1=avanthi(40)
t1.display()
Ex:
class Student:
def __init__(self, rollno, name):
self.rollno = rollno
self.name = name
def displayStudent(self):
print "rollno : ", self.rollno, ", name: ", self.name
emp1 = Student(121, "Bhuvana Kruthi")
emp2 = Student(122, "Sai Sruthi")
emp1.displayStudent()
emp2.displayStudent()
Output:
1. rollno : 121 , name: Bhuvana Kruthi
2. rollno : 122 , name: Sai Sruthi
t1=test(20,30)
t2=test(20,30)
t3=test(50,60)
print("Object1 == Object2 ",t1.equals(t2))
print("Object1 == Object3 ",t1.equals(t3))
Output:
Object1 == Object2 True
Object1 == Object3 False
Built-in Class Attributes: - Every class defined in Python has some built-in
attributes associated with it. Like other attributes, these attributes can also be
accessed using dot operator.
.__dict__: The attributes gives a dictionary containing the class’s or object’s(with
whichever it is accessed) namespace.
Display Class Attributes and Methods: There are two ways to determine the
attributes in class. One way is by using the inbuilt function dir() .
dir(name_of_class) or
dir(instance_of_class)
Ex:
class Student:
def __init__(self, rollno, name):
self.rollno = rollno
self.name = name
def displayStudent(self):
print ("rollno : ", self.rollno, ", name: ", self.name)
emp1 = Student(121, "Bhuvana Kruthi")
print(dir(emp1))
output:
Types of Variables:
1. Instance variables (Object level variables)
2. static variables (Class level variables)
3. Local Variables (Method level variables)
1. Instance variables/Object level variables: separate copy, which are declared by
self
2. static variables/class level variable: in class variable directly is called static
variable
3. local variables: the variable in side a method for temparory requirement/method
variable.
Instance variable: -If the value of a variable is varied from object to object. for every
object a separate copy will be created
where we have to declare instance variables:
1. Inside constructor by using self variable
2. Inside instance method by using self variable
3. From Outside of the class by using object reference variable
How to access instance variables:
1. within the class by using self
2. from outside of the class by using object reference
object.variable name
How to delete instance variables:
1. with in the class
del self.variablename
2. outside the class
del objectreference.variablename
t1=Test()
t1.b=777
Test.a=888
t2=Test()
print(t1.a,t1.b)
print(t2.a,t2.b)
Note: by object reference if we access : instance
by class name if we access : static
various places to declare static variables:
1. inside class directly
2. inside constructor by using class name
3. inside instance method by using class name
4. inside class method by using cls variable or classname
5. inside static method by using class name
6. from outside of the class also
How to access static variables:
1. inside constructor : either by self or by classname
2. inside instance method : either by self or by classname
3. inside class method: either by cls or by class name
4. inside static method : by classname
5. outside of class : either by object reference or by classname
How to delete static variables:
del classname.variablename
But inside class method
del classname.variablename
del cls.variablename
Ex:
class Sample:
domain="Big Data Analystics"
def SetCourse(self,name):
#Defining an instance variable
self.name=name
#Declaring an Instance of class Sample
ob1=Sample()
#Declaring another Instance of class Sample
ob2=Sample()
ob1.SetCourse('Python')
ob2.SetCourse('Hadoop')
Ex:
class person:
def __init__(self):
self.name="ramesh" # public attribute
self.__regno=123 # private attribute
def display(self):
print("Name =",self.name)
print("Regd No=",self.__regno)
p=person()
#access public attribute outside class
print("Name=",p.name)
p.display()
#try to access private variable outside class but fails
print("Regd no=",p.__regno)
p.display()
output:
Name= ramesh
Name = ramesh
Regd No= 123
Traceback (most recent call last):
File "E:\sample\main1.py", line 14, in <module>
print("Regd no=",p.__regno)
AttributeError: 'person' object has no attribute '__regno'
Ex: Public,Protected, private example
class Sample():
def __init__(self):
self.__pri ="I am Private"
self._pro = "I am Protected"
self.pub = " I am public"
#creating an Instance of class Sample
Types of Methods:
1. Instance Methods
2. Class methods
3. Static methods
s=Student("ramesh",70)
s.display()
s.grade()
Ex:
class Kls(object):
def __init__(self, data):
self.data = data
#instance method
def printd(self):
print(self.data)
ik1 = Kls('arun')
ik2 = Kls('seema')
ik1.printd()
ik2.printd()
Output:
arun
seema
Class method: - Class methods are little different from these ordinary methods.
First, they are called by a class (not by instance of the class). Second, the first
argument of the class method is cls, not the the self.
Inside method implementation if we are using only static variables (without
instance variables) then we should go for class methods
atleast one instance variables --> instance method
not using any instance variable just we are using only static variables: class
methods
@classmethod --- decorator
cls means class cls must be required
Ex:
class Animal:
legs=4
@classmethod
def walk(cls,name):
print("{} walks with {} legs ".format(name,cls.legs))
Animal.walk("Dog")
Animal.walk("Cat")
Ex:
class Test:
count=0
def __init__(self):
t1=Test()
t2=Test()
t3=Test()
Test.noOfObjectsCreated()
t1= noOfObjectsCreated()
t2= noOfObjectsCreated()
t3= noOfObjectsCreated()
Ex:
class rect:
def __init__(self,length,breadth):
self.length=length
self.breadth=breadth
def area(self):
return self.length*self.breadth
@classmethod
def square(cls,side):
return cls(side,side)
s=rect.square(10)
print("area=",s.area())
output:
area= 100
Static method: - Static methods are similar to class methods. The only difference
is that a static method does not receive any additional arguments.
Inside method if we are not using instance variables and static variables
General utility methods ---> static methods
@staticmethod --- decorator/anotation
calling using object or classname
without using decorator the function calling classobject.method name
Remember that, a static method does not use the self variable and is defined
using a built-in function named staticmethod.
Python has a handy syntax, called a decorator, to make it easier to apply the
staticmethod function to the method function definition. The syntax for using
staticmethod decorator is given as
@staticmethod
def name(args…):
statements
Simple functions with no 'self' argument. Nested inside a class
Sample.add(10,20)
Sample.mul(10,20)
Sample.average(10,20)
Ex:
class Sample:
@staticmethod
def show1(attr):
print(attr)
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
print (person1.age)
print (person2.age)
class Test:
def modify(emp):
emp.esal=emp.esal+10000
emp.display()
e=Employee(100,"Ramesh",60000)
Test.modify(e)
Output:
Employee number : 100
Employee Name : Ramesh
Employee Salary : 70000
Inner Class: An inner class or nested class is a defined entirely within the body of
another class. If an object is created using a class, the object inside the root class
can be used. A class can have more than one inner classes. Without existing one
type of object if there is no change of existing another type of object, then we should
go for inner classes
Ex:
class Outer:
def __init__(self):
print("Outer class object creation")
class Inner:
def __init__(self):
print("Inner class Object creation..")
def m1(self):
print("Inner class method")
o=Outer()
i=o.Inner()
i.m1()
or
i=Outer().Inner()
i.m1()
Ex:
class Person:
def __init__(self,name,dd,mm,yyyy):
self.name=name
def display(self):
print("Name =",self.name)
self.dob.display()
class Dob:
def __init__(self,dd,mm,yyyy):
self.dd=dd
self.mm=mm
self.yyyy=yyyy
def display(self):
print("DOB={}/{}/{}".format(self.dd,self.mm,self.yyyy))
p=Person("ramesh",8,5,1978)
p.display()
Ex:
class Human:
def __init__(self):
self.name = 'Ramesh'
self.head = self.Head()
self.brain = self.Brain()
class Head:
def talk(self):
return 'talking...'
class Brain:
def think(self):
return 'thinking...'
t = Human()
print (t.name)
print (t.head.talk())
print (t.brain.think())
output:
Ramesh
talking...
thinking...
def getVariableName(self):
return self.variableName
Ex:
class Student:
def setName(self,name):
self.name=name
def getName(self):
return self.name
def setMarks(self,marks):
self.marks=marks
def getMarks(self):
return self.marks
l=[]
n=int(input("enter the number of students:"))
for i in range(n):
s=Student()
name=input("enter Name of the student: ")
marks=int(input("enter Marks of the student: "))
s.setName(name)
s.setMarks(marks)
l.append(s)
for s in l:
print("Student Name: ",s.getName())
Ex:
class Sample:
def __init__(self,val):
self.val=val
def get_val(self):
return self.val
def set_val(self,val):
self.val=val
s=Sample(10)
s.set_val(20)
print(s.get_val())
output:
20
s=Sample(10)
s.val=20
print(s.val)
output:
20
Note: A method which is used for getting a value is decorated with @property.
Similarly, the method which sets a value of an instance variable – setter is
decorated with @x. setter, where x is the name of the function.
Another way:
Ex:
class Sample:
def __init__(self,val):
self.val=val
def get_val(self):
return self.__val
def set_val(self,val):
self.__val=val
val=property(get_val,set_val)
s=Sample(10)
s.val=20
print(s.val)
Ex: private getter and setter methods
class Sample:
def __init__(self,val):
self.val=val
def __get_val(self):
return self.__val
def __set_val(self,val):
self.__val=val
val=property(__get_val,__set_val)
s=Sample(10)
s.val=20
print(s.val)
Ex:
class Student:
def __init__(self,first_name,last_name):
self.__first_name=first_name
self.__last_name=last_name
@property
def name(self):
return ("%s %s" %(self.__first_name,self.__last_name))
s=Student("Ramesh","Kumar")
print(s.name)
The Key role of a delete is to delete the attribute from our object. However, note that
the getter,setter and delete methods must all have the same name as shonw in the
program given below
Ex:
class Sample:
def __init__(self,val):
self.val=val
@property
def val(self):
return self.__val
t1=Test()
print("Using t1 based on our requirement")
time.sleep(5)
print("Work with t1 completed making eligible for gc")
t1=None
time.sleep(10)
print("End of applicaton")
output:
Object Initializtion ...
The __del__()method:
The __del__()method is automatically called when an object is goint out of
scope. This is the time when an object will no longer be used and its occupied
resources are returned back to the system so that they can be reused as and when
required.
The __del__() method is analogous to destructors in C++ and Java
Ex:
class avanthi:
x=0
def __init__(self,k):
avanthi.x=avanthi.x+1
self.k=k
print("The object value is : ",k)
print("The value of class variable is :",avanthi.x)
def __del__(self):
avanthi.x=avanthi.x-1
print("Object with value %d is going out of scope"%self.k)
t1=avanthi(10)
t2=avanthi(20)
t3=avanthi(30)
del t1
del t2
del t3
Output:
The object value is : 10
The value of class variable is : 1
The object value is : 20
The value of class variable is : 2
The object value is : 30
The value of class variable is : 3
Object with value 10 is going out of scope
Object with value 20 is going out of scope
Object with value 30 is going out of scope
Ex:
class Sample:
def __init__(self,name):
self.name=name
def __del__(self):
print("Destrcutor started")
Operator Overloading:
the same built-in operator or function shows different behavior for objects of
different classes, this is called Operator Overloading.
Ex:
# Python program to show use of
# + operator for different purposes.
print(1 + 2)
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.
Ex:
class Sample:
def __init__(self,x):
self.x=x
x1=Sample(10)
x2=Sample(20)
print(x1+x2)
output:
X&Y __and__(self,other)
X|Y __or__(self,other)
X^Y __xor__(self,other)
~X _invert(self)
X<<Y __lshift__(self,other)
X>>Y __rshift__(self,other)
X&=Y __iand__(self,other)
X|=Y __ior__(self,other)
X^=Y __ixor__(self,other)
~=X _iinvert(self)
X<<=Y __ilshift__(self,other)
X>>=Y __irshift__(self,other)
class Complex:
def __init__(self,real,imag):
self.real=real
self.imag=imag
def __add__(self,other):
return Complex(self.real+other.real,self.imag+other.imag)
def __sub__(self,other):
return Complex(self.real-other.real,self.imag-other.imag)
def __mul__(self,other):
m=self.real*other.real-self.imag*other.imag
n=self.real*other.imag+self.imag*other.real
return Complex(m,n)
def __eq__(self,other):
return self.real==other.real and self.imag==other.imag
def __le__(self,other):
return self.real<other.real and self.imag<other.imag
def __ge__(self,other):
return self.real>other.real and self.imag>other.imag
output :
enter the first complex number real value2
enter the first complex number imag value1
enter the second complex number real value5
enter the second complex number imag value6
The first complex number
( 2 +i 1 )
The second complex number
( 5 +i 6 )
Additon value :
( 7 +i 7 )
Subtraction value :
( -3 +i -5 )
Multiplication value :
( 4 +i 17 )
Compare two Complex numbers :
False
Checking if c1 is Greater than c2:
False
Checking if c1 is Less than c2:
True
Top-down
Doctor Patient approach
Specialized class
Types of Inheritance:
The five types of inheritance are:
1. Single inheritance
2. Multiple inheritance
3. Multilevel inheritance
4. Hierarchical inheritance
5. Multipath inheritance
6. Hybrid inheritance
1. In single inheritance there is only one base class (super class) and only one
derived class(super class)
X
Y
2. In multiple inheritance there is only one derived class that is derived from
several base classes i.e., there are several base classes but only one derived
class.
X Y
3. In multi level inheritance the class is derived from the derived class
Z
4. In hierarchical inheritance there is only one base class but many derived
classes. These derived classes are derived only from one base class.
W Y Z
Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology
Python Programming 32
5. In Multipath inheritance
X
W Z
Y
Note: Every class in Python is derived from the object class. The object class is
defined in the Python library.
What is object class?
Like Java Object class, in Python (from version 3.x), object is root of all classes.
In Python 3.x, “class Test(object)” and “class Test” are same.
In Python 2.x, “class Test(object)” creates a class with object as parent (called new
style class) and “class Test” creates old style class (without object parent).
Syntax:
class DerivedClassName(BaseClassName):
<statement-1>
.
.
.
<statement-N>
Ex:
class avanthi1:
def assign1(self,x):
self.x=x
class avanthi2(avanthi1):
def assgin2(self,y):
self.y=y
def display(self):
print("x value=",self.x,"y value=",self.y)
t1=avanthi2()
t1.assign1(5)
t1.assgin2(20)
t1.display()
output: x value= 5 y value= 20
Ex:
class sample:
def setValues(self,x,y):
class sample1(sample):
def display(self):
print("X value=",self.x,"Y value=",self.y)
t1=sample1()
t1.setValues(20,30)
t1.display()
output:
X value= 20 Y value= 30
Ex:
class Animal:
def eat(self):
print 'Eating...'
class Dog(Animal):
def bark(self):
print 'Barking...'
d=Dog()
d.eat()
d.bark()
Output:
1. Eating...
2. Barking...
Output:
Eating...
Barking...
Weeping
class Derived(Base):
pass # Empty Class
# Driver Code
print(issubclass(Derived, Base))
print(issubclass(Base, Derived))
d = Derived()
b = Base()
Multiple Inheritance:
Syntax :
class Base1:
statement block
class Base2:
statement block
class Derived(Base1,Base2):
statement block
class Base2:
pass
class MultiDerived(Base1, Base2):
pass
Example:
class MySuperClass1():
def method_super1(self):
print("method_super1 method called")
class MySuperClass2():
def method_super2(self):
print("method_super2 method called")
class ChildClass(MySuperClass1,MySuperClass2):
def child_method(self):
print("child method")
c = ChildClass()
c.method_super1()
c.method_super2()
output:
method_super1 method called
method_super2 method called
Ex:
class First(object):
def __init__(self):
super(First, self).__init__()
class Second(object):
def __init__(self):
super(Second, self).__init__()
print("second")
Third();
Output:
first
second
third
Method Overriding:
In a class hierarchy, when a method in a sub class has the same name nd same
header as that of a super class then the method in the sub class is said to override
the method in the super class. When an overridden method is called, it always
invokes the method defined by its subclass. The same method defined by the super
class is hidden.
Ex:
class avanthi1:
def display(self):
print("Hai Students")
class avanthi2(avanthi1):
def display(self):
print("Hello Students")
t1=avanthi2()
t1.display()
output:
Hello Students
Ex: using super() key word call the super class method
class avanthi1:
def display(self):
print("Hai Students")
class avanthi2(avanthi1):
def display(self):
print("Hello Students")
super().display()
t1=avanthi2()
t1.display()
output:
Multipath Inheritance:
Let's look at Python. The first Diamond Problem configuration is like this: Both B
and C override the method m of A:
class A:
def m(self):
print ("m of A called")
class B(A):
def m(self):
print ("m of B called")
class C(A):
x=D()
x.m()
If you call the method m on an instance x of D, i.e. x.m(), we will get the output "m
of B called". If we transpose the order of the classes in the class header of D in
"class D (C, B):", we will get the output "m of C called".
The case in which m will be overridden only in one of the classes B or C, e.g. in C:
class A:
def m(self):
print("m of A called")
class B(A):
pass
class C(A):
def m(self):
print("m of C called")
class D(B,C):
pass
x = D()
x.m()
Principially, two possibilities are imaginable: "m of C" or "m of A" could be used
We call this script with Python2.7 (python) and with Python3 (python3) to see
what's happening:
$ python diamond1.py
m of A called
$ python3 diamond1.py
m of C called
class B(A):
def m(self):
print("m of B called")
class C(A):
def m(self):
print("m of C called")
class D(B,C):
def m(self):
print("m of D called")
Let's apply the method m on an instance of D. We can see that only the code of the
method m of D will be executed. We can also explicitly call the methods m of the
other classes via the class name, as we demonstrate in the following interactive
Python session:
>>> from super1 import A,B,C,D
>>> x = D()
>>> B.m(x)
m of B called
>>> C.m(x)
m of C called
>>> A.m(x)
m of A called
Now let's assume that the method m of D should execute the code of m of B, C and
A as well, when it is called. We could implement it like this:
class D(B,C):
def m(self):
print("m of D called")
B.m(self)
C.m(self)
A.m(self)
But it turns out once more that things are more complicated than it seems. How
can we cope with the situation, if both m of B and m of C will have to call m of A as
class B(A):
def m(self):
print("m of B called")
A.m(self)
class C(A):
def m(self):
print("m of C called")
A.m(self)
class D(B,C):
def m(self):
print("m of D called")
B.m(self)
C.m(self)
One way to solve this problem - admittedly not a Pythonic one - consists in splitting
the methods m of B and C in two methods. The first method, called _m consists of
the specific code for B and C and the other method is still called m, but consists
now of a call "self._m()" and a call "A.m(self)". The code of the method m of D
consists now of the specific code of D 'print("m of D called")', and the calls
B._m(self), C._m(self) and A.m(self):
class A:
def m(self):
print("m of A called")
class B(A):
def _m(self):
print("m of B called")
def m(self):
class C(A):
def _m(self):
print("m of C called")
def m(self):
self._m()
A.m(self)
class D(B,C):
def m(self):
print("m of D called")
B._m(self)
C._m(self)
A.m(self)
Our problem is solved, but - as we have already mentioned - not in a pythonic way:
>>> from super4 import D
>>> x = D()
>>> x.m()
m of D called
m of B called
m of C called
m of A called
The optimal way to solve the problem, which is the "super" pythonic way, consists
in calling the super function:
class A:
def m(self):
print("m of A called")
class B(A):
def m(self):
print("m of B called")
super().m()
class C(A):
def m(self):
print("m of C called")
super().m()
class D(B,C):
def m(self):
print("m of D called")
super().m()
The super function is often used when instances are initialized with the __init__
method:
class A:
def __init__(self):
print("A.__init__")
class B(A):
def __init__(self):
print("B.__init__")
super().__init__()
class C(A):
def __init__(self):
print("C.__init__")
super().__init__()
class D(B,C):
def __init__(self):
print("D.__init__")
super().__init__()
The question arises how the super functions makes its decision. How does it decide
which class has to be used? As we have already mentioned, it uses the so-called
method resolution order(MRO). It is based on the "C3 superclass linearisation"
algorithm. This is called a linearisation, because the tree structure is broken down
into a linear order. The mro method can be used to create this list:
>>> from super_init import A,B,C,D
>>> D.mro()
[<class 'super_init.D'>, <class 'super_init.B'>, <class 'super_init.C'>, <class
'super_init.A'>, <class 'object'>]
>>> B.mro()
[<class 'super_init.B'>, <class 'super_init.A'>, <class 'object'>]
>>> A.mro()
[<class 'super_init.A'>, <class 'object'>]
super () keyword:
Ex: Without super keyword
class demo:
a=b=c=0
def __init__(self,x,y,z):
self.a=x
self.b=y
self.c=z
def display(self):
print(self.a,self.b,self.c)
class demo1(demo):
d=0
def __init__(self,x,y,z,l):
self.a=x
self.b=y
self.c=z
self.d=l
def display(self):
print(self.a,self.b,self.c,self.d)
b1=demo(100,200,300)
print("Contents of Base class ")
b1.display()
b2=demo1(10,20,30,40)
print("Contents of Derived class")
b2.display()
output:
Contents of Base class
100 200 300
class demo1(demo):
d=0
def __init__(self,x,y,z,l):
self.d=l
super().__init__(x,y,z)
def display(self):
print(self.a,self.b,self.c,self.d)
b1=demo(100,200,300)
print("Contents of Base class ")
b1.display()
b2=demo1(10,20,30,40)
print("Contents of Derived class")
b2.display()
output:
Contents of Base class
100 200 300
Contents of Derived class
10 20 30 40
Super() keyword:
class A:
def m1(self):
print("A Class Method")
class B(A):
def m1(self):
print("B Class Method")
e=E()
e.m1()
output:
D Class Method
class A:
def m1(self):
print("A Class Method")
class B(A):
def m1(self):
print("B Class Method")
class C(B):
def m1(self):
print("C Class Method")
class D(C):
def m1(self):
print("D Class Method")
class E(D):
def m1(self):
B.m1(self)
e=E()
e.m1()
output:
B Class Method
Another way:
super(D,self).m1() call to D super class
Note:
1. From child class by using super() we cannnot call parent class instance variables
we should use self only.
2. From child class by using super() method we can call parent class static variables
class P:
def __init__(self):
print("Parent constructor")
class C(P):
def __init__(self):
super().__init__()
super().m1()
super().m2()
super().m3()
c=C()
output:
Parent constructor
Parent instance method
Parent class method
Parent static method
Ex:
class P:
def __init__(self):
print("Parent constructor")
def m1(self):
print("Parent instance method")
@classmethod
def m2(cls):
print("Parent class method")
@staticmethod
def m3():
print("Parent static method")
class C(P):
def method1(self):
super().__init__()
super().m1()
super().m2()
super().m3()
c=C()
c.method1()
output:
Data Hiding:
An object's attributes may or may not be visible outside the class definition. You
need to name attributes with a double underscore prefix, and those attributes then
are not be directly visible to outsiders.
Ex:
class avanthi:
__x = 0
def count(self):
self.__x += 1
print (self.__x)
t1 = avanthi()
t1.count()
t1.count()
print (t1.__x)
output:
1
2
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python36-32\add.py",
line 9, in <module>
print (t1.__x)
AttributeError: 'avanthi' object has no attribute '__x'
Python protects those members by internally changing the name to include the
class name. You can access such attributes as object._className__attrName. If you
would replace your last line as following, then it works for you:
print (t1._avanthi__x)
.
Exception Handling:
Errors: The errors can be divided into two types : compilation errors and runtime
errors
Compilation Errors:
Errors that occur during compilation are called compilation errors or syntax errors.
These errors are usually easy to detect because the compiler tells you where they
are (including line numbers) and the reasons for them.
Runtime Errors:
Runtime errors are the errors that cause a program to terminate abnormally. The
following are the main reasons for runtime errors:
a) Input errors b) System errors or Hardware errors c)Logical errors
a) Input Errors:
Handling Exceptions: -
Exception can be said to be any abnormal condition in a program resulting to the
disruption in the flow of the program.
Whenever an exception occurs the program halts the execution and thus further
code is not executed. Thus exception is that error which python script is unable to
tackle with.
Exception in a code can also be handled. In case it is not handled, then the code is
not executed further and hence execution stops when exception occurs.
We can halndle exception in our program by using try block and except block. Ac
critical operation which can raise exception is placed inside the try block and the
code that handles exception is written in excpeton block.
try:
statements
except ExceptionName:
Ex:
a=10
b=5
c=5
try:
x=a/(b-c)
print(x)
except ZeroDivisionError:
print("Divison by zero")
Ex:
try:
a=10/0
print (a)
except ArithmeticError:
print ("This statement is raising an exception")
else:
print ("Welcome")
Hierarchy Of Exception:
1. ZeroDivisionError: Occurs when a number is divided by zero.
2. NameError: It occurs when a name is not found. It may be local or global.
3. IndentationError: If incorrect indentation is given.
4. IOError: It occurs when Input Output operation fails.
5. EOFError: It occurs when end of file is reached and yet operations are being
performed
etc..
try:
The else Clause: - The try… except block can optionally have an else caluse, which
when present, must follow all except blocks. The statements in the else block is
executed only if the try clause doest not raise an exception.
try:
code
except:
code
else:
code
Finally Block:
In case if there is any code which the user want to be executed, whether exception
occurs or not then that code can be placed inside the finally block. Finally block will
always be executed irrespective of the exception.
Syntax:
try:
Code
finally:
code which is must to be executed.
Ex:
try:
a=10/0;
print "Exception occurred"
finally:
print "Code to be executed"
Output:
In the above example finally block is executed. Since exception is not handled
therefore exception occurred and execution is stopped.
Raising Exceptions:
You can expclictly throw an exception in Python using raise statement. raise will
cause an exception to occur and thus execution control will stop in case it is not
handled.
Syntax:
raise[Exception[,args[,traceback]]]
Ex:
try:
a=10
print a
raise NameError("Hello")
except NameError as e:
print "An exception occurred"
print e
Output:
10
An exception occurred
Hello
Explanation:
i) To raise an exception, raise statement is used. It is followed by exception class
name.
ii) Exception can be provided with a value that can be given in the parenthesis.
(here, Hello)
iii) To access the value "as" keyword is used. "e" is used as a reference variable
which stores the value of the exception.
Re-Raising Excepiton:
Python allows programmers to re-raise an exception. For example, an exception
thrown from the try block can be handled as well as re-raised in the except block
using the keyword raise.
Exceptions are two types
i) Built-in Exceptions
ii) User-defined Exceptions
Built-in Exception:
Python Built-in Exceptions
Exception Cause of Error
AssertionError Raised when assert statement fails.
AttributeError Raised when attribute assignment or reference fails.
EOFError Raised when the input() functions hits end-of-file condition.
FloatingPointError Raised when a floating point operation fails.
GeneratorExit Raise when a generator's close() method is called.
ImportError Raised when the imported module is not found.
IndexError Raised when index of a sequence is out of range.
KeyError Raised when a key is not found in a dictionary.
KeyboardInterrupt Raised when the user hits interrupt key (Ctrl+c or delete).
MemoryError Raised when an operation runs out of memory.
NameError Raised when a variable is not found in local or global scope.
NotImplementedError Raised by abstract methods.
OSError Raised when system operation causes system related error.
OverflowError Raised when result of an arithmetic operation is too large to be represented.
Raised when a weak reference proxy is used to access a garbage collected
ReferenceError
referent.
RuntimeError Raised when an error does not fall under any other category.
Raised by next() function to indicate that there is no further item to be
StopIteration
returned by iterator.
SyntaxError Raised by parser when syntax error is encountered.
IndentationError Raised when there is incorrect indentation.
TabError Raised when indentation consists of inconsistent tabs and spaces.
SystemError Raised when interpreter detects internal error.
SystemExit Raised by sys.exit() function.
TypeError Raised when a function or operation is applied to an object of incorrect type.
Raised when a reference is made to a local variable in a function or method,
UnboundLocalError
but no value has been bound to that variable.
UnicodeError Raised when a Unicode-related encoding or decoding error occurs.
UnicodeEncodeError Raised when a Unicode-related error occurs during encoding.
UnicodeDecodeError Raised when a Unicode-related error occurs during decoding.
UnicodeTranslateError Raised when a Unicode-related error occurs during translating.
ValueError Raised when a function gets argument of correct type but improper value.
Output:
CHAPTER
6
Syllabus:
Brief Tour of the Standard Library - Operating System Interface - String Pattern
Matching, Mathematics, Internet Access, Dates and Times, Data Compression,
Multithreading, GUI Programming, Turtle Graphics Testing: Why testing is required
OS Module:
Operating system interface:
The OS module in Python provides a way of using operating system
dependent functionality.
The functions that the OS module provides allows you to interface with the
underlying operating system that Python is running on – be that Windows,
Mac or Linux.
You can find important information about your location or about the process.
OS functions
1. Executing a shell command
os.system()
2. Returns the current working directory.
os.getcwd()
3. Return the real group id of the current process.
os.getgid()
4. Return the current process‟s user id.
os.getuid()
5. Returns the real process ID of the current process.
os.getpid()
6. Set the current numeric umask and return the previous umask.
os.umask(mask)
7. Return information identifying the current operating system.
os.uname()
8. Change the root directory of the current process to path.
os.chroot(path)
9. Return a list of the entries in the directory given by path.
os.listdir(path)
10. Create a directory named path with numeric mode mode.
os.mkdir(path)
11. Remove (delete) the file path.
os.remove(path)
12. Remove directories recursively.
os.removedirs(path)
13. Rename the file or directory src to dst.
os.rename(src, dst)
Examples:
1. getcwd()
import os
print(os.getcwd())
output: D:\pyexamples
2. listdir(), mkdir()
import os
os.mkdir("D:\\pyexamples\\ramesh2")
Note: In the above problem, it returns the space as word because ‘*’ returns zero or
more different matches. In order to remove space, we will go with ‘+’
import re
t=re.findall("\w+","If Good Programmer then you can be Good Developer")
print(t)
output:
['If', 'Good', 'Programmer', 'then', 'you', 'can', 'be', 'Good', 'Developer']
Example 3: Extract only first word from the sentence.
import re
t=re.findall("^\w+","If Good Programmer then you can be Good Developer")
print(t)
output:
['If']
The time Module: There is a popular time module available in Python which
provides functions for working with times and for converting between
representations. Here is the list of all available methods:
Sr.
No. Function with Description
time.ctime([secs])
1 Like asctime(localtime(secs)) and without arguments is like asctime(
)
calendar.leapdays(y1,y2)
4 Returns the total number of leap days in the years within
range(y1,y2).
calendar.month(year,month,w=2,l=1)
5 Returns a multiline string with a calendar for month of year, one
line per week plus two header lines. w is the width in characters
of each date; each line has length 7*w+6. l is the number of
lines for each week.
Example:
import calendar
print ("Here it is the calendar:")
print (calendar.month(2019,10))
calendar.setfirstweekday(6)
print (calendar.month(2019,10))
print ("Is 2019 is leap year?",calendar.isleap(2019))
print ("No.of Leap days",calendar.leapdays(2000,2019))
print ("1990-November-12 is",calendar.weekday(1990,11,12))
Output:
Here it is the calendar:
October 2019
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
October 2019
Su Mo Tu We Th Fr Sa
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Internet Access:
Simple Mail Transfer Protocol (SMTP) is a protocol, which handles sending
e-mail and routing e-mail between mail servers.
Python provides smtplib module, which defines an SMTP client session
object that can be used to send mail to any Internet machine with an SMTP
or ESMTP listener daemon.
Here is a simple syntax to create one SMTP object, which can later be used
to send an e- mail:
import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
Here is the detail of the parameters:
host: This is the host running your SMTP server. You can specify IP
address of the host or a domain name like tutorialspoint.com. This is
optional argument.
port: If you are providing host argument, then you need to specify a
port, where SMTP server is listening. Usually this port would be 25.
local_hostname: If your SMTP server is running on your local machine,
then you can specify just localhost as of this option.
An SMTP object has an instance method called sendmail, which is typically
used to do the work of mailing a message. It takes three parameters:
The sender - A string with the address of the sender.
The receivers - A list of strings, one for each recipient.
The message - A message as a string formatted as specified in the various
RFCs.
import smtplib
from email.mime.text import MIMEText
body="The message you want to send........"
msg=MIMEText(body)
fromaddr="rameshkumar123y@gmail.com"
toaddr="yrameshkumar123@gmail.com"
msg['From']=fromaddr
Example:
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def init (self, threadID, name, counter):
threading.Thread.init(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print ("Starting " + self.name)
print_time(self.name, self.counter, 5)
print ("Exiting ") + self.name
def print_time(threadName, delay, counter):
while counter:
if exitFlag:
thread.exit()
time.sleep(delay)
print (threadName, time.ctime(time.time()))
counter -= 1
GUI Programming
Python provides various options for developing graphical user interfaces
(GUIs). Most important are listed below:
Tkinter: Tkinter is the Python interface to the Tk GUI toolkit shipped with
Python..
wxPython: This is an open-source Python interface for wxWindows
http://wxpython.org.
JPython: JPython is a Python port for Java which gives Python scripts
seamless access to Java class libraries on the local machine
http://www.jython.org.
There are many other interfaces available, which you can find them on the net.
Write a program to display the Tkinter window with title
from tkinter import Tk
root = Tk()
root.title("CSE Students window")
root.mainloop()
The pack method is then called to organize the geometry of the control (label)
2. Customize Label
import tkinter
MainWindow = tkinter.Tk()
s1="Hello, CSE students very good, but \n results very ?"
l1=tkinter.Label(MainWindow,text=s1,fg="red",bg="yellow",font="Arial 10 bold")
l1.pack()
3. Button
import tkinter
MainWindow = tkinter.Tk()
b1=tkinter.Button(MainWindow,text="Close",width=20,command=MainWindo
w.destroy)
b1.pack()
4. ListBox
import tkinter
MainWindow = tkinter.Tk()
l1=tkinter.Listbox(MainWindow,width=20)
countries=['Italy','Brazil','Germany','France','Argentina','Spain']
l1.pack()
for i in countries:
l1.insert(l1.size(),i)
5. Spin Box
import tkinter
MainWindow = tkinter.Tk()
l1=tkinter.Label(MainWindow,text="Choose Month:",font='Arial 10 bold')
l1.pack()
sb1=tkinter.Spinbox(MainWindow,from_=1,to_=12,width=15)
sb1.pack()
6. Combo Box
The combobox is a dropdown list that provides a graphical way for the user to select
one value of the list. To use the Combobox control, we need to import the tkinter.ttk
module.
8. Entry
import tkinter
root = tkinter.Tk()
l1=tkinter.Label(root,text="Enter Your Name",font="Arial 10 bold")
l1.pack(side="left")
e1=tkinter.Entry(root)
e1.pack(side="right")
Example:
import tkinter
from tkinter import *
def DisplayMsg(self):
root.tkMessageBox.showinfo("Your Name","Welcome "+e1.get()+" "+e2.get())
root=Tk()
Label(root,text="Frist Name").grid(row=0)
e1=Entry(root)
e2=Entry(root)
e1.grid(row=0,column=1)
e2.grid(row=1,column=1)
e1.focus()
Button(root,text="Disp",command=DisplayMsg).grid(row=3,column=0)
Button(root,text="Close",command=root.destroy).grid(row=3,column=1)
mainloop()
output:
Example:
import tkinter
import tkMessageBox
top = tkinter.Tk()
def helloCallBack():
tkMessageBox.showinfo( "Hello Python", "Hello World")
B = Tkinter.Button(top, text ="Hello", command = helloCallBack)
B.pack()
top.mainloop()
output:
def equals():
try:
s=e.get()
for i in range(0,len(s)):
if s[i]=="+" or s[i]=="-" or s[i]=="*" or s[i]=="/" or s[i]=="%":
expr=str(float(s[:i]))+s[i:]
break
elif s[i]==".":
expr=s
break
e.delete(0,END)
e.insert(0,eval(expr))
except Exception:
back1=Button(root,text="<--",command=lambda:clear1(),width=10)
back1.grid(row=1,column=1,columnspan=2)
sqr=Button(root,text=u'\u221A',command=lambda:sqroot(),width=4)
sqr.grid(row=1,column=5)
can=Button(root,text="C",command=lambda:clear(),width=4)
can.grid(row=1,column=3)
neg=Button(root,text="+/-",command=lambda:negation(),width=4)
neg.grid(row=1,column=4)
nine=Button(root,text="9",command=lambda:setText("9"),width=4)
nine.grid(row=2,column=1)
eight=Button(root,text="8",command=lambda:setText("8"),width=4)
eight.grid(row=2,column=2)
seven=Button(root,text="7",command=lambda:setText("7"),width=4)
seven.grid(row=2,column=3)
six=Button(root,text="6",command=lambda:setText("6"),width=4)
six.grid(row=3,column=1)
five=Button(root,text="5",command=lambda:setText("5"),width=4)
five.grid(row=3,column=2)
four=Button(root,text="4",command=lambda:setText("4"),width=4)
four.grid(row=3,column=3)
three=Button(root,text="3",command=lambda:setText("3"),width=4)
three.grid(row=4,column=1)
two=Button(root,text="2",command=lambda:setText("2"),width=4)
two.grid(row=4,column=2)
one=Button(root,text="1",command=lambda:setText("1"),width=4)
zero=Button(root,text="0",command=lambda:setText("0"),width=10)
zero.grid(row=5,column=1,columnspan=2)
dot=Button(root,text=".",command=lambda:setText("."),width=4)
dot.grid(row=5,column=3)
div=Button(root,text="/",command=lambda:setText("/"),width=4)
div.grid(row=2,column=4)
mul=Button(root,text="*",command=lambda:setText("*"),width=4)
mul.grid(row=3,column=4)
minus=Button(root,text="-",command=lambda:setText("-"),width=4)
minus.grid(row=4,column=4)
plus=Button(root,text="+",command=lambda:setText("+"),width=4)
plus.grid(row=5,column=4)
mod=Button(root,text="%",command=lambda:setText("%"),width=4)
mod.grid(row=2,column=5)
byx=Button(root,text="1/x",command=lambda:setText("%"),width=4)
byx.grid(row=3,column=5)
equal=Button(root,text="=",command=lambda:equals(),width=4,height=3)
equal.grid(row=4,column=5,rowspan=2)
root.mainloop()
output:
Turtle Graphics
Graphics is the discipline that underlies the representation and display of
geometric shapes in two and three-dimensional space.
A Turtle graphics library provides an enjoyable and easy way to draw
shapes in a window and gives you an opportunity to run several functions
with an object.
Turtle graphics were originally developed as part of the children‟s
programming language called
Logo, created by Seymour Papert and his colleagues at MIT in the late 1960s.
Imagine a turtle crawling on a piece of paper with a pen tied to its tail.
Commands direct the turtle as it moves across the paper and tells it to lift
or lower its tail, turn some number of degrees left or right and move a
specified distance.
Whenever the tail is down, the pen drags along the paper, leaving a trail.
In the context of computer, of course, the sheet of paper is a window on a
display screen and the turtle is an invisible pen point.
At any given moment of time, the turtle coordinates. The position is
specified with (x, y) coordinates.
The coordinate system for turtle graphics is the standard Cartesian system,
with the origin (0, 0) at the centre of a window. The turtle‟s initial position is
the origin, which is also called the home.
Turtle Operations:
Turtle is an object; its operations are also defined as methods. In the below
table the list of methods of Turtle class.
radians Set the angle measurement unit, i.e., set the number
of degrees for a full circle. The default value is 3600.
seth Sets the orientation of the turtle to to_angle.
Turtle Object:
t=Turtle( ) creates a new turtle object and open sits window. The window‟s
drawing area is 200 pixels wide and 200 pixels high.
t=Turtle( width, height ) creates a new turtle object and open sits window. The
window‟s drawing area has given width and height.
Instructions Meaning
turtle.forward(number) Move forward
turtle.back(number) Move backward
turtle.forward(70)
turtle.left(120)
turtle.forward(70)
output:
Example: Write a program to draw a red color thick pen on a yellow background
import turtle
c=["red","green","blue"]
i=0
turtle.pensize(5)
for angle in range(0,360,30):
if i>2:
i=0
turtle.color(c[i])
turtle.seth(angle)
turtle.circle(50)
i=i+1
Example:
import turtle
for i in range(36):
for j in range(4):
turtle.forward(70)
turtle.left(90)
turtle.left(10)
Software Learn what it means and what its relationship is with Software
Quality Quality Control. Software Quality Assurance is a set of activities
Assuranc for ensuring quality in software engineering processes.
e
Learn what it means and what its relationship is with Software
Software
Quality Assurance. Software Quality Control is a set of activities
Quality
for ensuring quality in software products.
Control
Learn the differences between Software Quality Assurance and
SQA and
Software Quality Control. SQA is process-focused and prevention-
SQC
oriented but SQC is product-focused and detection-oriented.
Differences
Software Learn what SDLC means and what activities a typical SDLC model
Developmen comprises of. Software Development Life Cycle defines the
t Life Cycle steps/stages/phases in the building of software.
Software Learn what STLC means and what activities a typical STLC model
Testing comprises of. Software Testing Life Cycle (STLC) defines the
Life Cycle steps/ stages/ phases in testing of software.
Just as every field has its myths, so does the field of Software
Software
Testing. We explain some of the myths along with their related
Testing
facts.
Myths
Unit testing in Python:
The first unit testing framework, JUnit was invented by Kent Back and Erich
Gamma in 1997, for testing Java programs. It was so successful that the
framework has been implemented again in every major programming language.
Here we discuss the python version, unit test.
Unit testing is nothing but testing individual „units‟, or functions of a
program. It does not have a lot to say about system integration, whether the
various parts of a program fit together. That‟s a separate issue.
The goals of unit testing framework are:
To make it easy to write tests. All a „test‟ needs to do is to say that, for this
input, the
function should give that result. The framework takes care of running the
tests.
To make it easy to run tests. Usually this is done by clicking a single
button or typing a single keystroke (F5 in IDLE). Ideally, you should be
comfortable running tests after every change in the program, however
minor.
To make it easy to tell if the tests passed. The framework takes care of
reporting results; it either simply indicates that all tests passed, or it
provides a detailed list of failures.
Writing and Running Test cases
Your object is to write test and not to prove that your program works, it‟s
to try to find out where it doesn‟t! Test every „extreme‟ case you can think
of.
For example, if you were to write and test a function to sort a list, then the
first and last elements get moved to correct position? Can you sort a 1-
element list without getting an error? How about an empty list?
While you can put as many tests as you like into one test method that you
shouldn‟t test methods should be short and single-purpose. If you are
testing different aspects of a function, they should be in separate tests.
Here are the rules for writing test methods:
o The name of a test method must start with the letters „test‟, otherwise
it will be
ignored.
o This is so that you can write „helper‟ methods you can call from your
tests, but
are not directly called by the test framework.
o Every test method must have exactly one parameter, which is
assertNotEqual(a, b) a != b
assertIs(a, b) a is b
assertIsNot(a, b) a is not b
assertIsNone(x) x is None
assertIn(a, b) a in b
assertNotIn(a, b) a not in b
assertIsInstance(a, b) isinstance(a, b)
class TestAdd(unittest.TestCase):
unittest.main()
output:
.
----------------------------------------------------------------------
Ran 1 test in 0.017s
OK