0% found this document useful (0 votes)
92 views

Python Complete Course

The document discusses a Python course covering topics such as introduction to Python, variable declarations, condition execution, functions, modules, sequences, strings, sets, dictionaries, file I/O, errors and exceptions, namespaces and scope, objects and classes, inheritance, network and multithreading programming.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
92 views

Python Complete Course

The document discusses a Python course covering topics such as introduction to Python, variable declarations, condition execution, functions, modules, sequences, strings, sets, dictionaries, file I/O, errors and exceptions, namespaces and scope, objects and classes, inheritance, network and multithreading programming.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 124

PYTHON COURSE

BY
NANDAKUMAR P
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
CHAPTER 1: INTRODUCTION TO 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)
CHAPTER 1CONTINUES…

 Python Features:
Easy-to-learn
Easy-to-read
Easy-to-maintain
A broad standard library
Interactive mode
Portable
Extendable
Databases
GUI Programming
Scalable
CHAPTER 1CONTINUES…

 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)
CHAPTER 1CONTINUES…
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
CHAPTER 2: VARIABLE DECLARATIONS

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
CHAPTER 2 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
CHAPTER 2 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


CHAPTER 2 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


CHAPTER 2 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
CHAPTER 2 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)
CHAPTER 2 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']
CHAPTER 2 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
CHAPTER 2 CONTINUES… - OPERATORS
 Arithmetic Operators
+ Addition
- Subtraction
/ Division
* Multiplication
// Floor Division
% Modulus
** Exponent
 Comparison Operators (Relational)
==
!=
<>
>
<
>=
<=
CHAPTER 2 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
CHAPTER 2 CONTINUES… - OPERATORS

 Logical Operators
and (Logical AND)
or (Logical OR)
not Logical NOT
 Membership Operators
in
not in

 Identity Operators
 is
 is not
CHAPTER 2 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
CHAPTER 3 – CONDITION EXECUTION

 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.
CHAPTER 3 CONTINUES…. CONDITION EXECUTION

 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.
CHAPTER 3 CONTINUES…. CONDITION EXECUTION

 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!“)
CHAPTER 3 CONTINUES…. CONDITION EXECUTION

 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)
CHAPTER 3 CONTINUES…. CONDITION EXECUTION

 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!"


CHAPTER 3 CONTINUES…. CONDITION EXECUTION

 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 −

Example:
if expression1:
var = 100
statement(s) if var < 200:
if expression2: print "Expression value is less than 200"
statement(s) if var == 150:
print "Which is 150"
elif expression3: elif var == 100:
statement(s) print "Which is 100"
elif expression4: elif var == 50:
statement(s) print "Which is 50"
elif var < 50:
else: print "Expression value is less than 50"
statement(s) else:
else: print "Could not find true expression"
statement(s)
print "Good bye!"
CHAPTER 3 CONTINUES…. CONDITION EXECUTION

 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!“)


CHAPTER 3 CONTINUES…. CONDITION EXECUTION

 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!“)


CHAPTER 3 CONTINUES…. CONDITION EXECUTION

 Python programming language allows to use one loop inside another loop.
 Syntax (Nested Loop)
 For Loop
for iterating_var in sequence:
Example:
for iterating_var in sequence:
statements(s) i=2
statements(s) while(i < 100):
 While Loop
j=2
while(j <= (i/j)):
while expression:
if not(i%j): break
while expression: j=j+1
statement(s) if (j > i/j) : print (i, " is prime“)
statement(s) i=i+1

print "Good bye!"


CHAPTER 3 CONTINUES…. CONDITION EXECUTION

 Loop Control Statements


 Loop control statements change execution from its normal sequence.

 break
Example: It terminates the current loop
 continue and resumes execution at the next
 pass 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!"


CHAPTER 3 CONTINUES…. CONDITION EXECUTION

 Loop Control Statements


 Loop control statements change execution from its normal sequence.

 break Example: It returns the control to the beginning of the


 continue while loop. The continue statement rejects all the
 pass 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!"
CHAPTER 3 CONTINUES…. CONDITION EXECUTION

 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!“)


CHAPTER 4 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]
CHAPTER 4 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")
CHAPTER 4 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)
CHAPTER 4 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 ))
CHAPTER 4 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)
CHAPTER 4 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)
CHAPTER 5 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 ): def add(a,b):


print ("Hello : ", par) result=a+b
return return result
CHAPTER 5 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
CHAPTER 6 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 “:”

PYTHON SEQUENCE FUNCTIONS


 len() – return a numeric value of the given input
 min() and max() –return the minimum and maximum
numeric value
PYTHON SEQUENCE METHODS

 Python index()
 Python count()
CHAPTER 6 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.
CHAPTER 6 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.


CHAPTER 6 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)
CHAPTER 6 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.
CHAPTER 7 PYTHON STRINGS, SETS AND DICTIONARY

 Python Set
 Python Strings

 Python Dictionaries
CHAPTER 7 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.


CHAPTER 7 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.
CHAPTER 7 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.
CHAPTER 7 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.
CHAPTER 7 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.
CHAPTER 7 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.
CHAPTER 7 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


CHAPTER 8 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])
CHAPTER 8 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).
CHAPTER 8 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.
CHAPTER 8 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.
CHAPTER 8 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])
CHAPTER 9 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.
CHAPTER 9 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.
CHAPTER 9 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.
CHAPTER 9 EXCEPTIONS

Example: 1

try:

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

b = int(input("Enter b:"))

c = a/b

except:

print("Can't divide with zero")


CHAPTER 9 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")
CHAPTER 9 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
CHAPTER 9 EXCEPTIONS
Example:3

try:

a=10/0;

except(ArithmeticError, IOError):

print("Arithmetic Exception")

else:

print("Successfully Done")
CHAPTER 9 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
CHAPTER 9 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")
CHAPTER 9 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.
CHAPTER 9 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))
CHAPTER 10 NAMESPACE AND SCOPE

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
CHAPTER 10 NAMESPACE AND SCOPE

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.
CHAPTER 10 NAMESPACE AND SCOPE

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.
CHAPTER 10 NAMESPACE AND SCOPE

Example: Single Definition


>>> x = 'global'

>>> def f():


...
... def g():
... print(x)
...
... g()
...

>>> f()
global
CHAPTER 10 NAMESPACE AND SCOPE

Example: Double Definition


>>> x = 'global'

>>> def f():


... x = 'enclosing'
...
... def g():
... print(x)
...
... g()
...

>>> f()
enclosing
CHAPTER 10 NAMESPACE AND SCOPE

Example: Triple Definition


>>> x = 'global'

>>> def f():


... x = 'enclosing'
...
... def g():
... x = 'local'
... print(x)
...
... g()
...

>>> f()
local
CHAPTER 10 NAMESPACE AND SCOPE

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
CHAPTER 10 NAMESPACE AND SCOPE

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.
CHAPTER 10 NAMESPACE AND SCOPE

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 ')
CHAPTER 10 NAMESPACE AND SCOPE

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)>}


CHAPTER 10 NAMESPACE AND SCOPE

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}


CHAPTER 10 NAMESPACE AND SCOPE

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. >>> my_list = ['foo', 'bar', 'baz']
>>> x = 20 >>> def f():
... my_list[1] = 'quux'
>>> def f(): ...
... x = 40 >>> f()
>>> my_list
... print(x)
['foo', 'quux', 'baz’]
...
>>> f() >>> my_list = ['foo', 'bar', 'baz']
>>> def f():
40 ... my_list = ['qux', 'quux']
>>> x ...
>>> f()
20 >>> my_list
['foo', 'bar', 'baz']
CHAPTER 11 OBJECTS AND CLASS

 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.


CHAPTER 11 OBJECTS AND CLASS
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.
CHAPTER 11 OBJECTS AND CLASS
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
CHAPTER 11 OBJECTS AND CLASS
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.


CHAPTER 11 OBJECTS AND CLASS
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.
CHAPTER 11 OBJECTS AND CLASS
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.
CHAPTER 11 OBJECTS AND CLASS

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.
CHAPTER 11 OBJECTS AND CLASS
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)
CHAPTER 11 OBJECTS AND CLASS
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.
CHAPTER 11 OBJECTS AND CLASS
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)
CHAPTER 11 OBJECTS AND CLASS
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…..


CHAPTER 11 OBJECTS AND CLASS

# 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"))


CHAPTER 11 OBJECTS AND CLASS
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.
CHAPTER 11 OBJECTS AND CLASS
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…
CHAPTER 11 OBJECTS AND CLASS

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__)


CHAPTER 12 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
CHAPTER 12 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()
CHAPTER 12 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()
CHAPTER 12 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.


CHAPTER 12 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.
CHAPTER 12 INHERITANCE

Use the super() Function

Python also has a super() function that will make the child class inherit all the
methods and properties from its parent:

Example

class Student(Person):

def __init__(self, fname, lname):

super().__init__(fname, lname)

By using the super() function, you do not have to use the name of the parent
element, it will automatically inherit the methods and properties from its parent.
CHAPTER 12 INHERITANCE

Add Properties:

Example

Add a property called graduationyear to the Student class:

class Student(Person):

def __init__(self, fname, lname):

super().__init__(fname, lname)

self.graduationyear = 2010
CHAPTER 12 INHERITANCE

In the example below, the year 2010 should be a variable, and passed into the
Student class when creating student objects. To do so, add another parameter in the
__init__() function:

Example

Add a year parameter, and pass the correct year when creating objects:

class Student(Person):

def __init__(self, fname, lname, year):

super().__init__(fname, lname)

self.graduationyear = year

x = Student(“Nandakumar", “Pandiyan", 2010)


CHAPTER 12 INHERITANCE

Add Methods:

Example

Add a method called welcome to the Student class:

class Student(Person):

def __init__(self, fname, lname, year):

super().__init__(fname, lname)

self.graduationyear = year

def welcome(self):

print("Welcome", self.firstname, self.lastname, "to the class of",


self.graduationyear)

If you add a method in the child class with the same name as a function in the
parent class, the inheritance of the parent method will be overridden.
CHAPTER 13 NETWORK PROGRAMMING

Python Network Services

 Python provides two levels of access to network services.

 At a low level, you can access the basic socket support in the underlying
operating system, which allows you to implement clients and servers for
both connection-oriented and connectionless protocols.

 Python also has libraries that provide higher-level access to specific


application-level network protocols, such as FTP, HTTP, and so on.

 What is Sockets?

 Sockets are the endpoints of a bidirectional communications channel.

 Sockets may communicate within a process, between processes on the


same machine, or between processes on different continents.
CHAPTER 13 NETWORK PROGRAMMING
S.No. Term & Description
1 Domain
The family of protocols that is used as the transport mechanism. These values are
constants such as AF_INET, PF_INET, PF_UNIX, PF_X25, and so on.

2 type
The type of communications between the two endpoints, typically
SOCK_STREAM for connection-oriented protocols and SOCK_DGRAM for
connectionless protocols.
3 protocol
Typically zero, this may be used to identify a variant of a protocol within a domain
and type.
4 hostname
The identifier of a network interface −
•A string, which can be a host name, a dotted-quad address, or an IPV6 address in
colon (and possibly dot) notation
•A string "<broadcast>", which specifies an INADDR_BROADCAST address.
•A zero-length string, which specifies INADDR_ANY, or
•An Integer, interpreted as a binary address in host byte order.
5 port
Each server listens for clients calling on one or more ports. A port may be a Fixnum
port number, a string containing a port number, or the name of a service.
CHAPTER 13 NETWORK PROGRAMMING

The socket Module

To create a socket, you must use the socket.socket() function available in

socket module, which has the general syntax −

s = socket.socket (socket_family, socket_type, protocol=0)

Here is the description of the parameters −

socket_family − This is either AF_UNIX or AF_INET.

socket_type − This is either SOCK_STREAM or SOCK_DGRAM.

protocol − This is usually left out, defaulting to 0.


CHAPTER 13 NETWORK PROGRAMMING
Server Socket Methods
S.No. Method & Description
1 s.bind()
This method binds address (hostname, port number pair) to
socket.
2 s.listen()
This method sets up and start TCP listener.
3 s.accept()
This passively accept TCP client connection, waiting until
connection arrives (blocking).
Client Socket Methods

S.No. Method & Description


1 s.connect()
This method actively initiates TCP server connection.
CHAPTER 13 NETWORK PROGRAMMING
General Socket Methods

S.No. Method & Description


1 s.recv()
This method receives TCP message
2 s.send()
This method transmits TCP message
3 s.recvfrom()
This method receives UDP message
4 s.sendto()
This method transmits UDP message
5 s.close()
This method closes socket
6 socket.gethostname()
Returns the hostname.
CHAPTER 13 NETWORK PROGRAMMING

A Simple Server
# This is server.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection
while True:
c, addr = s.accept() # Establish connection with client
print ('Got connection from', addr)
c.send(b'Thank you for connecting')
c.close() # Close the connection
CHAPTER 13 NETWORK PROGRAMMING

A Simple Client
# This is client.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.connect((host, port))
print (s.recv(1024))
s.close() # Close the socket when done

How to run?
# Following would start a server in background
$ python server.py &
# Once server is started run client as follows
$ python client.py
CHAPTER 13 NETWORK PROGRAMMING
Python Internet modules
A list of some important modules in Python Network/Internet
programming.
Protocol Common function Port No Python module
HTTP Web pages 80 httplib, urllib,
xmlrpclib
NNTP Usenet news 119 nntplib
FTP File transfers 20 ftplib, urllib
SMTP Sending email 25 smtplib
POP3 Fetching email 110 poplib
IMAP4 Fetching email 143 imaplib
Telnet Command lines 23 telnetlib
Gopher Document transfers 70 gopherlib, urllib
Protocol Common function Port No Python module
HTTP Web pages 80 httplib, urllib,
xmlrpclib
NNTP Usenet news 119 nntplib
CHAPTER 14 MULTITHREADING PROGRAMMING
Thread

In computing, a process is an instance of a computer program that is being


executed. Any process has 3 basic components:

 An executable program.

 The associated data needed by the program (variables, work space,


buffers, etc.)

 The execution context of the program (State of process)

A thread is an entity within a process that can be scheduled for execution.


Also, it is the smallest unit of processing that can be performed in an OS
(Operating System).
CHAPTER 14 MULTITHREADING PROGRAMMING
Running several threads is similar to running several different programs
concurrently, but with the following benefits −

 Multiple threads within a process share the same data space with the
main thread and can therefore share information or communicate with
each other more easily than if they were separate processes.

 Threads sometimes called light-weight processes and they do not


require much memory overhead; they are cheaper than processes.

A thread has a beginning, an execution sequence, and a conclusion. It has


an instruction pointer that keeps track of where within its context it is
currently running.
 It can be pre-empted (interrupted)

 It can temporarily be put on hold (also known as sleeping) while


other threads are running - this is called yielding.
CHAPTER 14 MULTITHREADING PROGRAMMING
Starting a New Thread

To spawn another thread, you need to call following method available in


thread module −

thread.start_new_thread ( function, args[, kwargs] )

 This method call enables a fast and efficient way to create new threads
in both Linux and Windows.

 The method call returns immediately and the child thread starts and calls
function with the passed list of args. When function returns, the thread
terminates.

 Here, args is a tuple of arguments; use an empty tuple to call function


without passing any arguments. kwargs is an optional dictionary of
keyword arguments.
CHAPTER 14 MULTITHREADING PROGRAMMING
The Threading Module
The threading module exposes all the methods of the thread module and
provides some additional methods −

 threading.activeCount() − Returns the number of thread objects that


are active.

 threading.currentThread() − Returns the number of thread objects in


the caller's thread control.

 threading.enumerate() − Returns a list of all thread objects that are


currently active.
CHAPTER 14 MULTITHREADING PROGRAMMING
In addition to the methods, the threading module has the Thread class that
implements threading. The methods provided by the Thread class are as
follows −
 run() − The run() method is the entry point for a thread.

 start() − The start() method starts a thread by calling the run method.

 join([time]) − The join() waits for threads to terminate.

 isAlive() − The isAlive() method checks whether a thread is still


executing.

 getName() − The getName() method returns the name of a thread.

 setName() − The setName() method sets the name of a thread.


CHAPTER 14 MULTITHREADING PROGRAMMING
Creating Thread Using Threading Module
To implement a new thread using the threading module, you have to do the
following −

 Define a new subclass of the Thread class.

 Override the __init__(self [,args]) method to add additional arguments.

 Then, override the run(self [,args]) method to implement what the


thread should do when started.

Once you have created the new Thread subclass, you can create an instance
of it and then start a new thread by invoking the start(), which in turn calls
run() method.
CHAPTER 14 MULTITHREADING PROGRAMMING
Example 1
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, 5, self.counter)
print ("Exiting " + self.name)
Program continues in next page….
CHAPTER 14 MULTITHREADING PROGRAMMING
def print_time(threadName, counter, delay):
while counter:
if exitFlag:
threadName.exit()
time.sleep(delay)
print ("%s: %s" % (threadName, time.ctime(time.time())))
counter -= 1
# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

# Start new Threads


thread1.start()
thread2.start()

print ("Exiting Main Thread“)


CHAPTER 14 MULTITHREADING PROGRAMMING
Example 2
# Python program to illustrate the concept of threading
# importing the threading module
import threading
def print_cube(num):
"""
function to print cube of given num
"""
print("Cube: {}".format(num * num * num))

def print_square(num):
"""
function to print square of given num
"""
print("Square: {}".format(num * num))
Program continues in next page….
CHAPTER 14 MULTITHREADING PROGRAMMING
if __name__ == "__main__":
# creating thread
t1 = threading.Thread(target=print_square, args=(10,))
t2 = threading.Thread(target=print_cube, args=(10,))

# starting thread 1
t1.start()
# starting thread 2
t2.start()

# wait until thread 1 is completely executed


t1.join()
# wait until thread 2 is completely executed
t2.join()
# both threads completely executed
print("Done!")
IMPORTANT WEBSITES
 https://www.learnpython.org/

 https://www.programiz.com/python-programming

 https://www.w3schools.com/python/

 https://www.tutorialspoint.com/python/index.htm

 https://www.python.org/about/gettingstarted/

 https://www.guru99.com/python-tutorials.html

 https://www.javatpoint.com/python-programs

 https://stackify.com/learn-python-tutorials/

 https://www.geeksforgeeks.org/python-programming-examples/

 https://beginnersbook.com/2018/02/python-programs/
THANK YOU

AND

ALL THE BEST

You might also like