Skip to main content
PYTHON COURSE
BY
NANDAKUMARP
TRA, VIT
COURSE CONTENT
1. INTRODUCTION TO PYTHON
2. VARIABLE DECLARATION
3. CONDITION EXECUTION
4. PYTHON FUNCTIONS
5. PYTHON MODULES
6. SEQUENCES
7. PYTHON STRINGS, SETS AND DICTIONARY
8. PYTHON FILE I/O
9. PYTHON ERRORS AND BUILT-IN EXCEPTIONS
10. PYTHON NAMESPACE AND SCOPE
11. PYTHON OBJECTS AND CLASS
12. PYTHON INHERITANCE
13. PYTHON – NETWORK PROGRAMMING
14. PYTHON – MULTITHREADING PROGRAMMING
CHAPTER1: INTRODUCTIONTO PYTHON
 Python is a
 cross-platform programming language
 free and open source
 general-purpose interpreted, interactive, object-oriented, and
high-level programming language
 Python was created by “Guido Van Rossum” in the year 1991
(late 1980’s)
CHAPTER1CONTINUES…
 Python Features:
Easy-to-learn
Easy-to-read
Easy-to-maintain
A broad standard library
Interactive mode
Portable
Extendable
Databases
GUI Programming
Scalable
CHAPTER1CONTINUES…
 Starting the Python
 Two ways:
1. Immediate mode
Typing python code in the command line >>>
2. Script mode
 Typing python code in a file, such a file is called script.
 Save script as filename.py (ends with .py extension – denotes
python file)
CHAPTER1CONTINUES…
Identifiers and Keywords in Python
Identifiers: Set of valid strings
Rules for identifiers in python
 First character must be letter or underscore (example: name or _name)
 Any additional characters can be alphanumeric or underscore
 Case-sensitive
Keywords: Different version of python has different keywords
(Updated python 3 version has 33 keywords)
Some of them are: and elif for def from del
break print try return continue
CHAPTER2: VARIABLEDECLARATIONS
Variables Declaration
Python Statement, Indentation and Comments
Python List (Ordered sequences of items)
Python Strings (Sequence of Unicode characters)
Python Set (Unordered collection of Unique Items)
Python Dictionary (Unordered collection of key-value pairs)
Conversion between data types
Python Input, Output and Import
Python Operators
CHAPTER2 CONTINUES…- VARIABLES
 Variables must be declared before they are used in program
 The equal sign (=) is used to assign values to variables
 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.
 Example:
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
print counter
print miles
print name
CHAPTER2 CONTINUES…- LIST
 A list contains items separated by commas and enclosed within square brackets ([]).
 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.
 Example:
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print list # Prints complete list
print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated listsprint name
CHAPTER2 CONTINUES…- TUPLE
 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, while tuples are enclosed in parentheses ( ( ) ) and
cannot be updated.
 Example:
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print tuple # Prints the complete tuple
print tuple[0] # Prints first element of the tuple
print tuple[1:3] # Prints elements of the tuple starting from 2nd till 3rd
print tuple[2:] # Prints elements of the tuple starting from 3rd element
print tinytuple * 2 # Prints the contents of the tuple twice
print tuple + tinytuple # Prints concatenated tuples
CHAPTER2 CONTINUES…- STRINGS
 Strings in Python are identified as a contiguous set of characters represented in the
quotation marks.
 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.
 The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator.
 Example:
str = 'Hello World!'
print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th
print str[2:] # Prints string starting from 3rd character
print str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string
CHAPTER2 CONTINUES…- SETS
 A set is an unordered collection of items.
 Every set element is unique (no duplicates) and must be immutable
(cannot be changed). Set can be enclosed within {}-curly braces.
 However, a set itself is mutable. We can add or remove items from it
 Example:
# Different types of sets in Python
# set of integers
my_set = {1, 2, 3}
print(my_set)
# set of mixed datatypes
my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)
CHAPTER2 CONTINUES…- 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.
 Example:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']
CHAPTER2 CONTINUES…- OPERATORS
 Operators are the constructs which can manipulate the value of
operands.
 Consider the expression 5 + 5 = 10. Here, 5 and 5 are called operands
and + is called operator.
 Types of Operator
Python language supports the following types of operators.
 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators
CHAPTER2 CONTINUES…- OPERATORS
 Arithmetic Operators
+ Addition
- Subtraction
/ Division
* Multiplication
// Floor Division
% Modulus
** Exponent
 Comparison Operators (Relational)
==
!=
<>
>
<
>=
<=
CHAPTER2 CONTINUES…- OPERATORS
 Assignment Operators
=
+= (Add AND)
-= (Subtract AND)
*= (Multiply AND)
/= (Divide AND)
%= (Modulus AND)
**= (Exponent AND)
//= (Floor AND)
 Bitwise Operators
& Binary AND
| Binary OR
^ Binary XOR
~ Binary Ones Complement
<< Binary Left Shift
>> Binary Right Shift
CHAPTER2 CONTINUES…- OPERATORS
 Logical Operators
and (Logical AND)
or (Logical OR)
not Logical NOT
 Membership Operators
in
not in
 Identity Operators
 is
 is not
CHAPTER2 CONTINUES…- IMPORT
Python import
 Module – is a file containing python definitions and statements
 Python module have a filename and end with the extension .py
Example:
import math
print(math.pi)
from math import pi
pi
CHAPTER3 – CONDITIONEXECUTION
 Decision making is anticipation of conditions occurring while execution of the
program and specifying actions taken according to the conditions.
 Decision structures evaluate multiple expressions which produce TRUE or
FALSE as outcome.
 You need to determine which action to take and which statements to execute if
outcome is TRUE or FALSE otherwise.
CHAPTER3 CONTINUES…. CONDITIONEXECUTION
 The if statement contains a logical expression using which data is compared and
a decision is made based on the result of the comparison.
 Syntax (If)
if expression:
statement(s)
 If the boolean expression evaluates to TRUE, then the block of statement(s)
inside the if statement is executed.
 If boolean expression evaluates to FALSE, then the first set of code after the
end of the if statement(s) is executed.
CHAPTER3 CONTINUES…. CONDITIONEXECUTION
 Example:
var1 = 100
if var1:
print ("1 - Got a true expression value“)
print (var1)
var2 = 0
if var2:
print ("2 - Got a true expression value“)
print (var2)
print ("Good bye!“)
CHAPTER3 CONTINUES…. CONDITIONEXECUTION
 An else statement can be combined with an if statement.
 An else statement contains the block of code that executes if the conditional
expression in the if statement resolves to 0 or a FALSE value.
 The else statement is an optional statement and there could be at most only one
else statement following if.
 Syntax (If Else)
The syntax of the if...else statement is −
if expression:
statement(s)
else:
statement(s)
CHAPTER3 CONTINUES…. CONDITIONEXECUTION
 Example
var1 = 100
if var1:
print ("1 - Got a true expression value“)
print var1
else:
print ("1 - Got a false expression value“)
print (var1)
var2 = 0
if var2:
print ("2 - Got a true expression value“)
print (var2)
else:
print ("2 - Got a false expression value“)
print (var2)
print "Good bye!"
CHAPTER3 CONTINUES…. CONDITIONEXECUTION
 In a nested if construct, you can have an if...elif...else construct inside another
if...elif...else construct.
 Syntax (Nested If .. Elif .. Else)
The syntax of the nested if...elif...else construct may be −
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
elif expression4:
statement(s)
else:
statement(s)
else:
statement(s)
Example:
var = 100
if var < 200:
print "Expression value is less than 200"
if var == 150:
print "Which is 150"
elif var == 100:
print "Which is 100"
elif var == 50:
print "Which is 50"
elif var < 50:
print "Expression value is less than 50"
else:
print "Could not find true expression"
print "Good bye!"
CHAPTER3 CONTINUES…. CONDITIONEXECUTION
 A loop statement allows us to execute a statement or group of statements
multiple times. The following diagram illustrates a loop statement
 A while loop statement in Python programming language repeatedly executes a
target statement as long as a given condition is true.
 Syntax (While Loop)
The syntax of a while loop in Python programming language is −
while expression:
statement(s)
Example:
count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1
print ("Good bye!“)
CHAPTER3 CONTINUES…. CONDITIONEXECUTION
 It has the ability to iterate over the items of any sequence, such as a list or a
string.
 Syntax (For Loop)
for iterating_var in sequence:
statements(s)
Example:
for letter in 'Python': # First Example
print ('Current Letter :', letter)
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # Second Example
print ('Current fruit :', fruit)
print ("Good bye!“)
CHAPTER3 CONTINUES…. CONDITIONEXECUTION
 Python programming language allows to use one loop inside another loop.
 Syntax (Nested Loop)
 For Loop
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
 While Loop
while expression:
while expression:
statement(s)
statement(s)
Example:
i = 2
while(i < 100):
j = 2
while(j <= (i/j)):
if not(i%j): break
j = j + 1
if (j > i/j) : print (i, " is prime“)
i = i + 1
print "Good bye!"
CHAPTER3 CONTINUES…. CONDITIONEXECUTION
 Loop Control Statements
 Loop control statements change execution from its normal sequence.
 break
 continue
 pass
Example: It terminates the current loop
and resumes execution at the next
statement, just like the traditional break
statement in C.
for letter in 'Python': # First Example
if letter == 'h':
break
print ('Current Letter :', letter)
var = 10 # Second Example
while var > 0:
print ('Current variable value :', var)
var = var -1
if var == 5:
break
print "Good bye!"
CHAPTER3 CONTINUES…. CONDITIONEXECUTION
 Loop Control Statements
 Loop control statements change execution from its normal sequence.
 break
 continue
 pass
Example: It returns the control to the beginning of the
while loop. The continue statement rejects all the
remaining statements in the current iteration of the loop
and moves the control back to the top of the loop.
for letter in 'Python': # First Example
if letter == 'h':
continue
print ('Current Letter :', letter)
print "Good bye!"
var = 10 # Second Example
while var > 0:
var = var -1
if var == 5:
continue
print ('Current variable value :', var)
print "Good bye!"
CHAPTER3 CONTINUES…. CONDITIONEXECUTION
 Loop Control Statements
 Loop control statements change execution from its normal sequence.
 break
 continue
 pass
Example: It is used when a statement is required syntactically but you do
not want any command or code to execute. The pass statement is a null
operation; nothing happens when it executes.
for letter in 'Python':
if letter == 'h':
pass
print ('This is pass block’)
print ('Current Letter :', letter)
print ("Good bye!“)
CHAPTER4 FUCNTIONS
 A function is a block of organized, reusable code that is used to perform a
single, related action. Functions provide better modularity for your application
and a high degree of code reusing.
 Defining a Function:
 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.
 The statement return [expression] exits a function, optionally passing back an
expression to the caller.
 A return statement with no arguments is the same as return None.
 Syntax:
def functionname( parameters ):
function_suite
return [expression]
CHAPTER4 FUCNTIONS
Example:
def printme( str ):
print (str)
Calling a Function:
def printme( str ):
print (str)
return
printme("I'm first call to user defined function!")
printme("Again second call to the same function")
Arbitrary Arguments:
def my_function(*kids):
print("The youngest child is " + kids[0])
print("The 2nd youngest child is " + kids[1])
print("The 3rd youngest child is " + kids[2])
my_function(“Anil", “Babu", “Chandru")
CHAPTER4 FUCNTIONS
Pass by reference vs value:
def changeme( mylist ):#function define
mylist.append([1,2,3,4]);
print ("Values inside the function: ", mylist)
return
mylist = [10,20,30];
changeme( mylist );#function call
print ("Values outside the function: ", mylist)
def changeme( mylist ):
mylist = [1,2,3,4]; #Assigning the values to the parameter
print ("Values inside the function: ", mylist)
return
mylist = [10,20,30];
changeme( mylist );
print ("Values outside the function: ", mylist)
CHAPTER4 FUCNTIONS
Anonymous Function: lambda
 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.
Syntax:
lambda [arg1 [,arg2,.....argn]]:expression
Example:
sum = lambda arg1, arg2: arg1 + arg2;
print ("Value of total : ", sum( 10, 20 ))
print ("Value of total : ", sum( 20, 20 ))
CHAPTER4 FUCNTIONS
return statement:
 The statement return [expression] exits a function, optionally passing back an
expression to the caller.
 A return statement with no arguments is the same as return None.
Syntax:
return varname;
Example:
def sum( arg1, arg2 ):#function is defined
total = arg1 + arg2
print ("Inside the function : ", total)
return total;
total = sum( 10, 20 );#function is called
print ("Outside the function : ", total)
CHAPTER4 FUCNTIONS
Global and Local Variables: (Scope of Variables)
 All variables in a program may not be accessible at all locations in that
program.
 This depends on where you have declared a variable.
Example:
total = 0; # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print ("Inside the function local total : ", total)
return total;
# Now you can call sum function
sum( 10, 20 );
print ("Outside the function global total : ", total)
CHAPTER5 MODULES
 A module allows you to logically organize your Python code.
 Grouping related code into a module makes the code easier to understand and
use.
 A module is a Python object with arbitrarily named attributes that you can
bind and reference.
 Simply, a module is a file consisting of Python code.
 A module can define functions, classes and variables.
 A module can also include runnable code.
Example: Save it as sample.py (here module name is sample)
def print_func( par ):
print ("Hello : ", par)
return
def add(a,b):
result=a+b
return result
CHAPTER5 MODULES
import statement
Syntax:
import module1[, module2[,... moduleN]
import sample
# Now you can call defined function that module as follows
sample.print_func(“CSC")
sample.add(5,5)
from...import Statement
Syntax:
from modname import name1[, name2[, ... nameN]]
dir( ) Function
import math
content = dir(math)
print content
CHAPTER6 SEQUENCES
 A sequence is a group of items with a deterministic ordering.
 The order in which we put them in is the order in which we get an
item out from them.
 Python offers six types of sequences.
1. Python Strings
2. Python Lists
3. Python Tuples
4. Bytes Sequences
5. Bytes Arrays
6. range() objects
PYTHON SEQUENCE OPERATIONS
 Concatenation “+”
 Integer Multiplication “*”
 Membership “in && not in”
 Python Slice “:”
 len() – return a numeric value of the given input
 min() and max() –return the minimum and maximum
numeric value
 Python index()
 Python count()
PYTHON SEQUENCE FUNCTIONS
PYTHON SEQUENCE METHODS
CHAPTER6 SEQUENCES
List Methods:
Methods Name Description
append() Add an element to the end of the list.
extend() Add all elements of a list to the another list.
insert() Insert an item at the defined index.
remove() Removes an item from the list.
pop() Removes and returns an element at the given index.
clear() Removes all items from the list.
index() Returns the index of the first matched item.
count() Returns the count of number of items passed as an
argument.
sort() Sort items in a list in ascending order.
reverse() Reverse the order of items in the list.
copy() Returns a shallow copy of the list.
CHAPTER6 SEQUENCES
Built-in Functions with List:
Function Name Description
all() Return true if all elements of the list are true (or if the list is
empty).
any() Return true if any element of the list is true. If the list is
empty, return false.
enumerate() Return an enumerate object. It contains the index and value
of all the items of list as a tuple.
len() Return the length (the number of items) in the list.
list() Convert an iterable (tuple, string, set, dictionary) to a list.
max() Return the largest item in the list.
min() Return the smallest item in the list.
sorted() Return a new sorted list (does not sort the list itself).
sum() Return the sum of all elements in the list.
CHAPTER6 SEQUENCES
Tuple Methods:
Methods Name Description
count(x) Return the number of items that is equal to x.
index(x) Return index of first item that is equal to x.
Example:
tup=(‘A’,’L’,’L’,’I’,’S’,’W’,’E’,’L’,’L’)
print(tup.count(‘L’))
print(tup.index(‘W’))
print(‘S’ in tup)
print(‘N’ not in tup)
CHAPTER6 SEQUENCES
Built-in Functions with Tuple:
Function Name Description
all() Return true if all elements of the tuple are true (or if the tuple
is empty).
any() Return true if any element of the tuple is true. If the tuple is
empty, return false.
enumerate() Return an enumerate object. It contains the index and value
of all the tuple as pairs.
len() Return the length (the number of items) in the tuple.
tuple() Convert an iterable (list, string, set, dictionary) to a tuple.
max() Return the largest item in the tuple.
min() Return the smallest item in the tuple.
sorted() Take elements in the tuple and return a new sorted tuple
(does not sort the tuple itself).
sum() Return the sum of all elements in the tuple.
CHAPTER7 PYTHONSTRINGS, SETSANDDICTIONARY
 Python Set
 Python Strings
 Python Dictionaries
CHAPTER7 CONTINUES…
Python Set Methods:
Methods Name Description
add() Add an element to a set.
clear() Remove all elements from a set.
copy() Return a shallow copy of a set.
difference() Return the difference of two or more sets as a new set.
difference_update() Remove all elements of another set from this set.
discard() Remove an element from set if it is a member.
intersection() Return the intersection of two sets as a new set.
intersection_update() Update the set with the intersection of itself and
another.
isdisjoint() Return true if two sets have a null intersection.
issubset() Return true if another set contains this set.
issuperset() Return true if this set contains another set.
CHAPTER7 CONTINUES…
Python Set Methods:
Methods Name Description
pop() Remove and return an arbitrary set element.
Raise KeyError if the set is empty.
remove() Remove an element from a set. If the
element is not a member, raise a KeyError.
symmetric_difference() Return the symmetric difference of two sets
as a new set.
symmetric_difference_update() Update a set with the symmetric difference
of itself and another.
union() Return the union of sets in a new set.
update() Update a set with the union of itself and
others.
CHAPTER7 CONTINUES…
Built-in Functions with Set:
Function Name Description
all() Return true if all elements of the set are true (or if the set is
empty).
any() Return true if any element of the set is true. If the set is
empty, return false.
enumerate() Return an enumerate object. It contains the index and value
of all the items of set as a pair.
len() Return the length (the number of items) in the set.
max() Return the largest item in the set.
min() Return the smallest item in the set.
sorted() Return a new sorted list from elements in the set (does not
sort the set itself).
sum() Return the sum of all elements in the set.
CHAPTER7 CONTINUES…
Python String Methods:
Methods Name Description
capitalize() It returns a copy of the string with only its first character
capitalized.
center() Returns centered in a string of length width.
count() Returns the number of occurrences of substring sub in the
range[start,end].
find() It determines if string str occurs in string, or in a substring of
string if starting index beg and ending index end are given.
replace() Returns a copy of the string in which the occurrence of old
have been replaced with new.
isalpha() Returns true if string has at least 1 character and all
characters are alphabetic and false otherwise.
isdigit() Returns true if string contains only digits and false
otherwise.
islower() Returns true if string has at least 1 cased character and all
cased characters are in lowercase and false otherwise.
CHAPTER7 CONTINUES…
Python String Methods:
Methods Name Description
isnumeric() Returns true if a Unicode string contains only numeric
characters and false otherwise.
istitle() Returns true if string is properly “titlecased” and false
otherwise.
isupper() Returns true if string has at least 1 cased character and all
cased characters are in uppercase and false otherwise.
len(string) Returns the length of the string.
lower() Converts all uppercase letters in string to lowercase.
lstrip() Removes all leading whitespace from left side of a string.
rstrip() Removes all leading whitespace to the right side of a string.
upper() Converts all lowercase letters in string to uppercase.
swapcase() It inverts case for all letters in string.
split() It split the given sentence into list of string.
join() It is used to join a list of string as a single sequence.
CHAPTER7 CONTINUES…
Python Dictionary Methods:
Methods Name Description
clear() Remove all elements from the dictionary.
copy() Return a shallow copy of a dictionary.
fromkeys(seq[,v]) Return a new dictionary with keys from seq and value equal to v
(defaults to None).
get(key[,d]) Return the value of key. If key doesn't exit, return d (defaults to
None).
items() Return a new view of the dictionary’s items (key,value).
keys() Return a new view of the dictionary’s keys.
pop(key[,d]) Remove the item with key and return its value or d, if key is not
found. If d is not provided and key is not found, raises KeyError.
popitem() Remove and return an arbitrary item (key,value). Raises KeyError
if the dictionary is empty.
setdefault(key[,d]) If key is in the dictionary, return its value. If not, insert key with a
value of d and return d (defaults to None).
update({key:value}) Update the dictionary with the key/value pairs from other
overwriting existing keys.
values() Return a new view of the dictionary’s values.
CHAPTER7 CONTINUES…
Built-in Functions with Dictionary:
Function Name Description
all() Return true if all keys of the dictionary are true (or if the
dictionary is empty).
any() Return true if any key of the dictionary is true. If the
dictionary is empty, return false.
len() Return the length (the number of items) in the dictionary.
sorted() Return a new sorted list of keys in the dictionary.
cmp() Compares items of two different dictionaries
CHAPTER8 FILES I/O
 Files is a collection of stored information in the local
disk.
 File operation
 Open a file
 Read or write
 Close the file
The open Function
 Before you can read or write a file, you have to open it using
Python's built-in open() function.
 This function creates a file object, which would be utilized to
call other support methods associated with it.
Syntax
file object = open(file_name [, access_mode][, buffering])
CHAPTER8 FILES I/O
Here are parameter details −
 file_name − The file_name argument is a string value that contains
the name of the file that you want to access.
 access_mode − The access_mode determines the mode in which the
file has to be opened, i.e., read, write, append, etc.
 buffering −
 If the buffering value is set to 0, no buffering takes place. If the buffering
value is 1, line buffering is performed while accessing a file.
 If you specify the buffering value as an integer greater than 1, then buffering
action is performed with the indicated buffer size.
 If negative, the buffer size is the system default(default behavior).
CHAPTER8 FILES I/O
Different modes of opening a file:
SNo. Modes & Description
1 r
Opens a file for reading only. The file pointer is placed at the beginning of the file.
This is the default mode.
2 rb
Opens a file for reading only in binary format. The file pointer is placed at the
beginning of the file. This is the default mode.
3 r+
Opens a file for both reading and writing. The file pointer placed at the beginning of
the file.
4 rb+
Opens a file for both reading and writing in binary format. The file pointer placed at
the beginning of the file.
5 w
Opens a file for writing only. Overwrites the file if the file exists. If the file does not
exist, creates a new file for writing.
6 wb
Opens a file for writing only in binary format. Overwrites the file if the file exists. If
the file does not exist, creates a new file for writing.
CHAPTER8 FILES I/O
Different modes of opening a file:
SNo. Modes & Description
7 w+
Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the
file does not exist, creates a new file for reading and writing.
8 wb+
Opens a file for both writing and reading in binary format. Overwrites the existing file if the
file exists. If the file does not exist, creates a new file for reading and writing.
9 a
Opens a file for appending. The file pointer is at the end of the file if the file exists. That is,
the file is in the append mode. If the file does not exist, it creates a new file for writing.
10 ab
Opens a file for appending in binary format. The file pointer is at the end of the file if the
file exists. That is, the file is in the append mode. If the file does not exist, it creates a new
file for writing.
11 a+
Opens a file for both appending and reading. The file pointer is at the end of the file if the
file exists. The file opens in the append mode. If the file does not exist, it creates a new file
for reading and writing.
12 ab+
Opens a file for both appending and reading in binary format. The file pointer is at the end
of the file if the file exists. The file opens in the append mode. If the file does not exist, it
creates a new file for reading and writing.
CHAPTER8 FILES I/O
 The close() Method
 The close() method of a file object flushes any unwritten information
and closes the file object, after which no more writing can be done.
 Python automatically closes a file when the reference object of a file is
reassigned to another file. It is a good practice to use the close() method
to close a file.
Syntax:
fileObject.close()
 The read() Method
 The read() method reads a string from an open file.
 It is important to note that Python strings can have binary data. apart
from text data.
Syntax:
fileObject.read([count])
CHAPTER9 EXCEPTIONS
Python provides two very important features to handle any unexpected
error in your Python programs and to add debugging capabilities in them −
1. Exception Handling - An exception is an event, which occurs during
the execution of a program that disrupts the normal flow of the program's
instructions.
In general, when a Python script encounters a situation that it cannot cope
with, it raises an exception.
An exception is a Python object that represents an error.
When a Python script raises an exception, it must either handle the
exception immediately otherwise it terminates and quits.
CHAPTER9 EXCEPTIONS
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.
ZeroDivisionError: Occurs when a number is divided by zero.
NameError: It occurs when a name is not found. It may be local or global.
IndentationError: If incorrect indentation is given.
IOError: It occurs when Input Output operation fails.
EOFError: It occurs when the end of the file is reached, and yet
operations are being performed.
CHAPTER9 EXCEPTIONS
Handling an exception:
Syntax
Here is simple syntax of try....except...else blocks −
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
CHAPTER9 EXCEPTIONS
Example: 1
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
except:
print("Can't divide with zero")
CHAPTER9 EXCEPTIONS
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 class
except Exception:
print("can't divide by zero")
print(Exception)
else:
print("Hi I am else block")
CHAPTER9 EXCEPTIONS
Declaring Multiple Exceptions
The Python allows us to declare the multiple exceptions with the except
clause.
Declaring multiple exceptions is useful in the cases where a try block
throws multiple exceptions.
The syntax is given below:
try:
#block of code
except (<Exception 1>,<Exception 2>,<Exception 3>,...<Exception n>):
#block of code
else:
#block of code
CHAPTER9 EXCEPTIONS
Example:3
try:
a=10/0;
except(ArithmeticError, IOError):
print("Arithmetic Exception")
else:
print("Successfully Done")
CHAPTER9 EXCEPTIONS
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.
The syntax to use the finally block is given below:
try:
# block of code
# this may throw an exception
finally:
# block of code
# this will always be executed
CHAPTER9 EXCEPTIONS
Example:4
try:
fileptr = open("sample2.txt","r")
try:
fileptr.write("Hi I am good")
finally:
fileptr.close()
print("file closed")
except:
print("Error")
CHAPTER9 EXCEPTIONS
2. Assertions - 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.
Assertions are carried out by the assert statement, the newest keyword to
Python, introduced in version 1.5.
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.
CHAPTER9 EXCEPTIONS
The assert Statement
When it encounters an assert statement, Python evaluates the
accompanying expression, which is hopefully true. If the expression is
false, Python raises an AssertionError exception.
The syntax for assert is −
assert Expression[, Arguments]
Example:
def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
return ((Temperature-273)*1.8)+32
print (KelvinToFahrenheit(273))
print (int(KelvinToFahrenheit(505.78)))
print (KelvinToFahrenheit(-5))
CHAPTER10 NAMESPACEANDSCOPE
Namespaces in Python
A namespace is a collection of currently defined symbolic names along with
information about the object that each name references.
You can think of a namespace as a dictionary in which the keys are the object
names and the values are the objects themselves.
Each key-value pair maps a name to its corresponding object.
In a Python program, there are four types of namespaces:
1. Built-In
2. Global
3. Enclosing
4. Local
CHAPTER10 NAMESPACEANDSCOPE
The Built-In Namespace
The built-in namespace contains the names of all of Python’s built-in objects.
These are available at all times when Python is running. You can list the objects in
the built-in namespace with the following command:
>>> dir(__builtins__)
The Global Namespace
The global namespace contains any names defined at the level of the main
program. Python creates the global namespace when the main program body starts,
and it remains in existence until the interpreter terminates.
CHAPTER10 NAMESPACEANDSCOPE
The Local and Enclosing Namespaces
In the previous topic on functions, the interpreter creates a new namespace
whenever a function executes.
That namespace is local to the function and remains in existence until the function
terminates.
Functions don’t exist independently from one another only at the level of the main
program.
When a function is defined inside a function, it creates an enclosed namespace. Its
lifecycle is the same as the local namespace.
CHAPTER10 NAMESPACEANDSCOPE
Example: Single Definition
>>> x = 'global'
>>> def f():
...
... def g():
... print(x)
...
... g()
...
>>> f()
global
CHAPTER10 NAMESPACEANDSCOPE
Example: Double Definition
>>> x = 'global'
>>> def f():
... x = 'enclosing'
...
... def g():
... print(x)
...
... g()
...
>>> f()
enclosing
CHAPTER10 NAMESPACEANDSCOPE
Example: Triple Definition
>>> x = 'global'
>>> def f():
... x = 'enclosing'
...
... def g():
... x = 'local'
... print(x)
...
... g()
...
>>> f()
local
CHAPTER10 NAMESPACEANDSCOPE
Example: No Definition
>>> def f():
...
... def g():
... print(x)
...
... g()
...
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in f
File "<stdin>", line 4, in g
NameError: name 'x' is not defined
CHAPTER10 NAMESPACEANDSCOPE
Variable Scope
The existence of multiple, distinct namespaces means several different instances of
a particular name can exist simultaneously while a Python program runs.
As long as each instance is in a different namespace, they’re all maintained
separately and won’t interfere with one another.
Suppose you refer to the name x in your code, and x exists in several
namespaces. How does Python know which one you mean?
The answer lies in the concept of scope.
The scope of a name is the region of a program in which that name has meaning.
The interpreter determines this at runtime based on where the name definition
occurs and where in the code the name is referenced.
CHAPTER10 NAMESPACEANDSCOPE
Example:
prog_var = 'Hello'
def outer_func():
outer_var = 'x'
def inner_func():
inner_var = 'y'
print(dir(), ' Local Variable in Inner function')
inner_func()
print(dir(), 'Local variables in outer function')
outer_func()
print(dir(), 'Global variables ')
CHAPTER10 NAMESPACEANDSCOPE
Python Namespace Dictionaries
The globals() function
The built-in function globals() returns a reference to the current global namespace
dictionary.
>>> type(globals())
<class 'dict'>
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None,
'__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None,
'__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}
CHAPTER10 NAMESPACEANDSCOPE
The locals() function
Python also provides a corresponding built-in function called locals(). It’s similar
to globals() but accesses objects in the local namespace instead:
>>> def f(x, y):
... s = 'foo'
... print(locals())
...
>>> f(10, 0.5)
{'s': 'foo', 'y': 0.5, 'x': 10}
CHAPTER10 NAMESPACEANDSCOPE
Modify Variables Out of Scope
Sometimes a function can modify its argument in the calling environment by
making changes to the corresponding parameter, and sometimes it can’t:
 An immutable argument can never be modified by a function.
 A mutable argument can’t be redefined wholesale, but it can be modified in
place.
>>> x = 20
>>> def f():
... x = 40
... print(x)
...
>>> f()
40
>>> x
20
>>> my_list = ['foo', 'bar', 'baz']
>>> def f():
... my_list[1] = 'quux'
...
>>> f()
>>> my_list
['foo', 'quux', 'baz’]
>>> my_list = ['foo', 'bar', 'baz']
>>> def f():
... my_list = ['qux', 'quux']
...
>>> f()
>>> my_list
['foo', 'bar', 'baz']
CHAPTER11 OBJECTS ANDCLASS
 Python is an object-oriented programming language.
 What this means is we can solve a problem in Python by creating
objects in our programs.
 Concepts of OOPs terms such as class, objects, methods etc. along with
the Object oriented programming features such as inheritance,
polymorphism, abstraction, encapsulation can be learned in this chapter.
CHAPTER11 OBJECTS ANDCLASS
Object
 An object is an entity that has attributes and behaviour.
 For example, CSC is an object who has attributes such as system, faculties,
classrooms etc. and has certain behaviours such as teaching, practicing,
evaluating etc.
Class
 A class is a blueprint for the objects.
 For example, CSC, NIIT, Infiniti, Infotech are all objects so we can define a
template (blueprint) class ComputerCentre for these objects.
 The class can define the common attributes and behaviours of all the objects.
Methods
 As we discussed above, an object has attributes and behaviours.
 These behaviours are called methods in programming.
CHAPTER11 OBJECTS ANDCLASS
Some points on Python class:
 Classes are created by keyword class.
 Attributes are the variables that belong to a class.
 Attributes are always public and can be accessed using the dot (.) operator. Eg.:
Myclass.Myattribute
Class Definition Syntax:
class ClassName:
# Statement-1
.
.
.
# Statement-N
CHAPTER11 OBJECTS ANDCLASS
An object consists of :
 State: It is represented by the attributes of an object. It also reflects the
properties of an object.
 Behavior: It is represented by the methods of an object. It also reflects the
response of an object to other objects.
 Identity: It gives a unique name to an object and enables one object to interact
with other objects.
CHAPTER11 OBJECTS ANDCLASS
Overview of OOP Terminology
Class − A user-defined prototype for an object that defines a set of attributes that
characterize any object of the class. The attributes are data members (class
variables and instance variables) and methods, accessed via dot notation.
Class variable − A variable that is shared by all instances of a class. Class
variables are defined within a class but outside any of the class's methods. Class
variables are not used as frequently as instance variables are.
Data member − A class variable or instance variable that holds data associated
with a class and its objects.
Function overloading − The assignment of more than one behavior to a particular
function. The operation performed varies by the types of objects or arguments
involved.
CHAPTER11 OBJECTS ANDCLASS
Overview of OOP Terminology
Instance variable − A variable that is defined inside a method and belongs only to
the current instance of a class.
Inheritance − The transfer of the characteristics of a class to other classes that are
derived from it.
Instance − An individual object of a certain class. An object obj that belongs to a
class Circle, for example, is an instance of the class Circle.
Instantiation − The creation of an instance of a class.
Method − A special kind of function that is defined in a class definition.
Object − A unique instance of a data structure that's defined by its class. An object
comprises both data members (class variables and instance variables) and methods.
Operator overloading − The assignment of more than one function to a particular
operator.
CHAPTER11 OBJECTS ANDCLASS
Creating Classes
The class statement creates a new class definition. The name of the class
immediately follows the keyword class followed by a colon as follows −
class ClassName:
'Optional class documentation string'
class_suite
 The class has a documentation string, which can be accessed via
ClassName.__doc__.
 The class_suite consists of all the component statements defining class
members, data attributes and functions.
CHAPTER11 OBJECTS ANDCLASS
Example:
Following is the example of a simple Python class −
class Employee:
'Common base class for all employees'
empCount = 0 #variable name
def __init__(self, name, salary):#predefined built-in functions
self.name = name
self.salary = salary
Employee.empCount += 1 #a=a+1 or a+=1
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)
CHAPTER11 OBJECTS ANDCLASS
Example: Explanation
The variable empCount is a class variable whose value is shared among all
instances of a this class.
This can be accessed as Employee.empCount from inside the class or outside the
class.
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.
CHAPTER11 OBJECTS ANDCLASS
Creating Instance Objects
To create instances of a class, you call the class using class name and pass in
whatever arguments its __init__ method accepts.
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
Accessing Attributes
You access the object's attributes using the dot operator with object. Class variable
would be accessed using class name as follows −
emp1.displayEmployee()
emp2.displayEmployee()
print ("Total Employee %d" % Employee.empCount)
CHAPTER11 OBJECTS ANDCLASS
Example of Class and Objects:
In this example, we have two objects Ram and Steve that belong to the class
Human
Object attributes: name, height, weight
Object behaviour: eating() --- method
class Human:
# instance attributes
def __init__(self, name, height, weight):
self.name = name
self.height = height
self.weight = weight
# instance methods (behaviours)
def eating(self, food):
return "{} is eating {}".format(self.name, food)
Program continues in next page…..
CHAPTER11 OBJECTS ANDCLASS
# creating objects of class Human
ram = Human(“Ram", 6, 60)
jaanu = Human(“Jaanu", 5.9, 56)
# accessing object information
print("Height of {} is {}".format(ram.name, ram.height))
print("Weight of {} is {}".format(ram.name, ram.weight))
print(ram.eating("Pizza"))
print("Weight of {} is {}".format(jaanu.name, jaanu.height))
print("Weight of {} is {}".format(jaanu.name, jaanu.weight))
print(jaanu.eating("Big Kahuna Burger"))
CHAPTER11 OBJECTS ANDCLASS
Built-In Class Attributes
Every Python class keeps following built-in attributes and they can be accessed
using dot operator like any other attribute −
__dict__ − Dictionary containing the class's namespace.
__doc__ − Class documentation string or none, if undefined.
__name__ − Class name.
__module__ − Module name in which the class is defined. This attribute is
"__main__" in interactive mode.
__bases__ − A possibly empty tuple containing the base classes, in the order of
their occurrence in the base class list.
CHAPTER11 OBJECTS ANDCLASS
Example using Built_In Class attributes:
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)
Program continues in next page…
CHAPTER11 OBJECTS ANDCLASS
print ("Employee.__doc__:", Employee.__doc__)
print ("Employee.__name__:", Employee.__name__)
print ("Employee.__module__:", Employee.__module__)
print ("Employee.__bases__:", Employee.__bases__)
print ("Employee.__dict__:", Employee.__dict__)
CHAPTER12 INHERITANCE
Python Inheritance
 Inheritance allows us to define a class that inherits all the methods and
properties from another class.
 Parent class is the class being inherited from, also called base class.
 Child class is the class that inherits from another class, also called
derived class.
Python Inheritance Syntax
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class
CHAPTER12 INHERITANCE
Create a Parent Class
Any class can be a parent class, so the syntax is the same as creating any other
class:
Example
Create a class named Person, with firstname and lastname properties, and a
printname method:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname
method:
x = Person(“Nandakumar", “Pandiyan")
x.printname()
CHAPTER12 INHERITANCE
Create a Child Class
To create a class that inherits the functionality from another class, send the parent
class as a parameter when creating the child class:
Example
Create a class named Student, which will inherit the properties and methods from
the Person class:
class Student(Person):
pass
#Use the Student class to create an object, and then execute the printname
method:
x = Student(“Aadhish", “Nandakumar")
x.printname()
CHAPTER12 INHERITANCE
Add the __init__() Function:
So far we have created a child class that inherits the properties and methods from
its parent.
We want to add the __init__() function to the child class (instead of the pass
keyword).
Note: The __init__() function is called automatically every time the class is
being used to create a new object.
Example
Add the __init__() function to the Student class:
class Student(Person):
def __init__(self, fname, lname):
#add properties etc.
CHAPTER12 INHERITANCE
When you add the __init__() function, the child class will no longer inherit the
parent's __init__() function.
Note: The child's __init__() function overrides the inheritance of the parent's
__init__() function.
To keep the inheritance of the parent's __init__() function, add a call to the parent's
__init__() function:
Example
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
Now we have successfully added the __init__() function, and kept the inheritance
of the parent class, and we are ready to add functionality in the __init__() function.