You are on page 1of 87

SRM Institute of Science and Technology

School of Computing

Advanced Programming Practice-18CSC207J

Presented by,
Mrs.S.Amudha
Paradigm types
Unit IV
– Functional Programming Paradigm [Text Book :1]
– Logic Programming Paradigm [Text Book : 1& 3]
– Dependent Type Programming Paradigm
– Network Programming Paradigm [ Text Book :4]

Text Book:

1. Elad Shalom, A Review of Programming Paradigms throughout the History: With a


suggestion Toward a Future Approach, Kindle Edition, 2018
2. John Goerzen, Brandon Rhodes, Foundations of Python Network Programming:
The comprehensive guide to building network applications with Python, 2nd ed.,
Kindle Edition, 2010
3. Amit Saha, Doing Math with Python: Use Programming to Explore Algebra,
Statistics,Calculus and More, Kindle Edition, 2015
Functional Programming Paradigm
Unit-III (15 Session)
Session 11-15 cover the following topics:-
– Definition - S11-SLO1
– Sequence of Commands – S11-SLO2
– map(), reduce(), filter(), lambda – S12-SLO1
– partial, functools – S12-SLO2
– Other languages:F#, Clojure, Haskell – S13-SLO1
– Demo: Functional Programming in Python - S13-SLO2

Lab 9: Functional Programming ( Case Study) (S14-15)

Assignment : Comparative study of Functional programming in F#,


Clojure, Haskell

– TextBook: Shalom, Elad. A Review of Programming Paradigms


Throughout the History: With a Suggestion Toward a Future Approach,
Kindle Edition
Functional Programming Paradigm ( TF1)

Definition
• Mainly treat computation to evaluate mathematical Functions
• Avoids changing-state and mutable data
• Called as declarative programming paradigm
• Output depends on argument passing
• Calling same function several times with same values produces
same result
• Uses expressions or declarations rather than statements as in
imperative languages
Concepts

• It views all subprograms as functions in the mathematical


sense
• Take in arguments and return a single solution.
• Solution returned is based entirely on input, and the time at
which a function is called has no relevance.
• The computational model is therefore one of function
application and reduction.
Characteristics of Functional Programming

• Functional programming method focuses on results, not the


process
• Emphasis is on what is to be computed
• Data is immutable
• Functional programming Decompose the problem into
'functions
• It is built on the concept of mathematical functions which
uses conditional expressions and recursion to do perform the
calculation
• It does not support iteration like loop statements and
conditional statements like If-Else
History
• The foundation for Functional Programming is Lambda Calculus.
It was developed in the 1930s for the functional application,
definition, and recursion
• LISP was the first functional programming language. McCarthy
designed it in 1960
• In the late 70's researchers at the University of Edinburgh defined
the ML(Meta Language)
• In the early 80's Hope language adds algebraic data types for
recursion and equational reasoning
• In the year 2004 Innovation of Functional language 'Scala.'
Real Time applications

• Database processing
• Financial modeling
• Statistical analysis and
• Bio-informatics
Functional Programming Languages

• Haskell
• SML
• Clojure
• Scala
• Erlang
• Clean
• F#
• ML/OCaml Lisp / Scheme
• XSLT
• SQL
• Mathematica
Basic Functional Programming Terminology and Concepts
Functional Vs Procedural
S.No Functional Paradigms Procedural Paradigm

1 Treats computation as the evaluation Derived from structured programming,


of mathematical based on the concept of modular
functions avoiding state and mutable data programming or the procedure call

2 Main traits are Lambda Main traits are Local variables, sequence,
calculus, compositionality, formula, recursio selection, iteration, and modularization
n, referential transparency
3 Functional programming focuses Procedural programming focuses
on expressions on statements
4 Often recursive. Always returns the same The output of a routine does not always
output for a given input. have a direct correlation with the input.

5 Order of evaluation is usually undefined. Everything is done in a specific order.

6 Must be stateless. i.e. No operation can have Execution of a routine may have side
side effects. effects.
7 Good fit for parallel execution, Tends to Tends to emphasize implementing
emphasize a divide and conquer approach. solutions in a linear fashion.
Functional Vs Object-oriented Programming
S.No Functional Paradigms Object Oriented Paradigm

1 FP uses Immutable data. OOP uses Mutable data.

2 Follows Declarative Programming based Follows Imperative Programming Model.


Model.
3 What it focuses is on: "What you are doing. in What it focuses is on "How you are
the programme." doing your programming."
4 Supports Parallel Programming. No supports for Parallel Programming.
5 Its functions have no-side effects. Method can produce many side effects.
6 Flow Control is performed using function calls Flow control process is conducted using
& function calls with recursion. loops and conditional statements.
7 Execution order of statements is not very Execution order of statements is
important. important.

8 Supports both "Abstraction over Data" and Supports only "Abstraction over Data".
"Abstraction over Behavior."
Functional Programming in Python

• Functional Programming is a popular programming paradigm


closely linked to computer science's mathematical
foundations. While there is no strict definition of what
constitutes a functional language, we consider them to be
languages that use functions to transform data.

• Python is not a functional programming language but it does


incorporate some of its concepts alongside other
programming paradigms. With Python, it's easy to write code
in a functional style, which may provide the best solution for
the task at hand.
Functional Programming in Python
Without any special Python features or libraries, we can start coding in a
more functional way. several important principles and concepts related to
functional programming:
1. Pure Functions
- do not have side effects, that is, they do not change the state of
the program. Given the same input, a pure function will always produce the
same output.
2. Immutability
- data cannot be changed after it is created
3. Higher Order Functions
- is a function that takes a function as an argument, or returns
a function .
4. Lambda Expressions
- (or lambda functions) are essentially blocks of code that can be
assigned to variables, passed as an argument, or returned from a function
call, in languages that support high-order functions
5. Recursive functions,
A recursive function is a function that calls itself during the
execution. For example, we can use recursion to find the
factorial in the functional style:
def factorial_r(n):
if n == 0:
return 1
return n * factorial_r(n — 1)
6. First class functions
1.Pure Functions

• is idempotent — returns the same result if provided


the same arguments,
• has no side effects.
• If a function uses an object from a higher scope or
random numbers, communicates with files and so on,
it might be impure
• Since its result doesn’t depend only on its arguments.
Example Pure Function
Ex. Impure function - using Python
• Anonymous functions are split into two types: lambda functions and closures.
• Functions are made of four parts: name, parameter list, body, and return
Example Code
Anonymous Functions

• Anonymous (lambda) functions can be very convenient


for functional programming constructs.
• They don’t have names and usually are created ad-hoc,
with a single purpose.
Immutable variables

• Immutable variable (object) is a variable whose state


cannot be modified once it is created.
• In contrast, a mutable variable can be modified after
it is created
Exp in java
• String str = “A Simple String.”;
• str.toLowerCase();
Higher-order function

• takes one or more functions as an input


• outputs a function
• Exp : Map Function
• Consider a function that prints a line multiple
times:
• Example Code
def write_repeat(message, n):
for i in range(n):
print(message)
write_repeat('Hello', 5)
Examples
Anonymous function assigned to a variable. Easy to pass around and
invoke when needed.
const myVar = function(){console.log(‘Anonymous function here!’)}
myVar()
Anonymous function as argument
• setInterval(function(){console.log(new Date().getTime())}, 1000);
Anonymous functions within a higher order function
function mealCall(meal){
return function(message){
return console.log(message + “ “ + meal + ‘!!’) }
}
const announceDinner = mealCall(‘dinner’)
const announceLunch = mealCall(‘breakfast’)
announceDinner(‘hey!, come and get your’)
announceLunch(‘Rise and shine! time for’)
Mathematical Background

• For example, if f(x)=x2and x is 3, the ordered pair is (-3,


9).
• A function is defined by its set of inputs, called the
domain.
• A set containing the set of outputs, and possibly
additional elements as members, is called its codomain.
• The set of all input-output pairs is called its graph.
Mathematical Background

General Concepts Functional Rules


• Notation
F(x) = y
x , y -> Arguments or 1. (f+g)(x)=f(x)+g(x)
parameters 2. (f-g)(x)=f(x)-g(x)
x -> domain and
3. (f*g)(x)=f(x)*g(x)
y->codomain
Types: 4. (f/g)(x)=f(x)/g(x)
– Injective if f(a) ≠ f(b) 5. (gof)(x)=g(f(x))
– Surjective if f(X)= Y 6. f f-1=idy
– Bijective ( support both)
Scenario1

def hof_write_repeat(message, n, action):


• What if we wanted to
write to a file 5 times, or for i in range(n):
log the message 5 times? action(message)
Instead of writing 3
different functions that hof_write_repeat('Hello', 5, print)
all loop, we can write 1
Higher Order Function
that accepts those # Import the logging library
functions as an import logging
argument: # Log the output as an error instead
hof_write_repeat('Hello', 5, logging.error)
Scenario2

• Imagine that we're


tasked with creating
functions that
increment numbers in a
list by 2, 5, and 10. So
instead of creating
many different
increment functions,
we create 1 Higher
Order Function:
Built-in Higher Order Functions
• Map
The map function allows us to apply a function to every element in
an iterable object
• Filter
The filter function tests every element in an iterable object with a
function that returns either True or False, only keeping those
which evaluates to True.
• Combining map and filter
As each function returns an iterator, and they both accept iterable
objects, we can use them together for some really expressive data
manipulations!
• List Comprehensions
A popular Python feature that appears prominently in Functional
Programming Languages is list comprehensions. Like the map and
filter functions, list comprehensions allow us to modify data in a
concise, expressive way.
Features of Functional paradigms

• First-class functions – accept another function as an argument


or return a function
• Pure functions - they are functions without side effects
• Recursion - allows writing smaller algorithms and operating by
looking only at the inputs to a function
• Immutable variables - variables that cannot be changed
• Non-strict evaluation - allows having variables that have not
yet been computed
• Statements - evaluable pieces of code that have a return value
• Pattern matching - allows better type-checking and extracting
elements from an object
First Class functions in Python
• First class objects in a language are handled uniformly
throughout. They may be stored in data structures, passed as
arguments, or used in control structures.
• A programming language is said to support first-class
functions if it treats functions as first-class objects. Python
supports the concept of First Class functions
Properties of first class functions:
• A function is an instance of the Object type.
• You can store the function in a variable.
• You can pass the function as a parameter to another function.
• You can return the function from a function.
• You can store them in data structures such as hash tables,
lists, …
Example
Procedural Programming
Functional Programming

num = 1 num = 1
def function_to_add_one(num): def procedure_to_add_one():
num += 1 global num
return num num += 1
return num
function_to_add_one(num)
procedure_to_add_one()
function_to_add_one(num)
procedure_to_add_one()
function_to_add_one(num) procedure_to_add_one()
function_to_add_one(num) procedure_to_add_one()
function_to_add_one(num) procedure_to_add_one()

#Final Output: 2 #Final Output: 6


Functional programming tools
• Built-in Higher Order Functions
Python has implemented some commonly used Higher Order
Functions from Functional Programming Languages that makes
processing iterable objects like lists and iterators much easier. For
space/memory efficiency reasons, these functions return an
iterator instead of a list.
• filter(function, sequence)
def f(x): return x%2 != 0 and x%3 ==0
filter(f, range(2,25))
• map(function, sequence)
– call function for each item
– return list of return values
• reduce(function, sequence)
– return a single value
– call binary function on the first two items
– then on the result and next item
– iterate
1. filter() in python
• The filter() method filters the given sequence with the help
of a function that tests each element in the sequence to be
true or not.
• syntax:

filter(function, sequence)

• Parameters:
• function: function that tests if each element of a sequence
true or not.
• sequence: sequence which needs to be filtered, it can
be sets, lists, tuples, or containers of any iterators.
• Returns:
returns an iterator that is already filtered.
Example1
Application:
• It is normally used with Lambda functions to
separate list, tuple, or sets.
Print vowels using filter
alphabets = ['a', 'b', 'd', 'e', 'i', 'j', 'o']
• # function that filters vowels
def filterVowels(alphabet):
vowels = ['a', 'e', 'i', 'o', 'u']
if(alphabet in vowels):
return True
else:
return False
filteredVowels = filter(filterVowels, alphabets)
print('The filtered vowels are:')
for vowel in filteredVowels:
print(vowel)
Example: Filter the array, and return a new array with
only the values equal to or above 18
2. Python map()

Python map() function


map() function returns a map object(which is an
iterator) of the results after applying the given
function to each item of a given iterable (list,
tuple etc.)

Syntax :
map(fun, iter)
Python program to demonstrate working
# of map.

# Return double of n
def addition(n):
return n + n
# We double all numbers using map()
numbers = (1, 2, 3, 4)
result = map(addition, numbers)
print(list(result))
---------------------------------------------------------------------------------
O/p - {2, 4, 6, 8}
• CODE 2
We can also use lambda expressions with map
to achieve above result.
#Double all numbers using map and lambda
numbers = (1, 2, 3, 4)
result = map(lambda x: x + x, numbers)
print(list(result))
O/p - {2, 4, 6, 8}
# Add two lists using map and lambda
numbers1 = [1, 2, 3]
numbers2 = [4, 5, 6]
result = map(lambda x, y: x + y, numbers1,
numbers2)
print(list(result))

Output :
[5, 7, 9]
Map
# List of strings
#Python map() function with multiple
arguments
• Take a look at the example of using map() function
with multiple iterable arguments.
• We have defined one list and iterator and passed
that to the map function, and it will return the
multiplication of that list and tuple and returns the
iterator, and we have converted that iterator to the
list.
Map with List and tuples
Return Value from map()
• The map() function applies a given to function
to each item of an iterable and returns a list of
the results.

• The returned value from map() (map object)


then can be passed to functions like list() (to
create a list), set() (to create a set) and so on.
3. Reduce() in Python
The reduce(fun,seq) function is used to apply a particular
function passed in its argument to all of the list elements
mentioned in the sequence passed along.This function is
defined in “functools” module.

Working :

• At first step, first two elements of sequence are picked and the
result is obtained.
• Next step is to apply the same function to the previously
attained result and the number just succeeding the second
element and the result is again stored.
• This process continues till no more elements are left in the
container.
• The final returned result is returned and printed on console.
# python code to demonstrate working of reduce()
# importing functools for reduce()
import functools
# initializing list
lis = [ 1 , 3, 5, 6, 2, ]
# using reduce to compute sum of list
print ("The sum of the list elements is : ",end="")
print (functools.reduce(lambda a,b : a+b,lis))
# using reduce to compute maximum element from list
print ("The maximum element of the list is : ",end="")
print (functools.reduce(lambda a,b : a if a > b else b,lis))
Output:
The sum of the list elements is : 17
The maximum element of the list is : 6
Using Operator Functions
• reduce() can also be combined with operator
functions to achieve the similar functionality as
with lambda functions and makes the code more
readable.
reduce() vs accumulate()
• Both reduce() and accumulate() can be used to calculate
the summation of a sequence elements. But there are
differences in the implementation aspects in both of these.

• reduce() is defined in “functools” module, accumulate() in


“itertools” module.
• reduce() stores the intermediate result and only returns the
final summation value. Whereas, accumulate() returns a list
containing the intermediate results. The last number of the
list returned is summation value of the list.
• reduce(fun,seq) takes function as 1st and sequence as 2nd
argument. In contrast accumulate(seq,fun) takes sequence
as 1st argument and function as 2nd argument.
Nested functions in Python

• A function which is defined inside another function is


known as nested function. Nested functions are able
to access variables of the enclosing scope.
• In Python, these non-local variables can be accessed
only within their scope and not outside their scope.
This can be illustrated by following example:
# Python program to illustrate
# nested functions
def outerFunction(text):
text = text
def innerFunction():
print(text)

innerFunction()

if __name__ == '__main__':
outerFunction('Hey!')
• As we can see innerFunction() can easily be accessed inside the
outerFunction body but not outside of it’s body. Hence, here,
innerFunction() is treated as nested Function which uses text as
non-local variable.
Python Closures

• A Closure is a function object that remembers values in


enclosing scopes even if they are not present in memory.

• It is a record that stores a function together with an


environment: a mapping associating each free variable of the
function (variables that are used locally, but defined in an
enclosing scope) with the value or reference to which the name
was bound when the closure was created.

• A closure—unlike a plain function—allows the function to


access those captured variables through the closure’s copies of
their values or references, even when the function is invoked
outside their scope.
# Python program to illustrate
# closures
def outerFunction(text):
text = text

def innerFunction():
print(text)

return innerFunction # Note we are returning function WITHOUT parenthesis

if __name__ == '__main__':
myFunction = outerFunction('Hey!')
myFunction()

O/p -Hey
When and why to use Closures:

As closures are used as callback functions, they provide some


sort of data hiding. This helps us to reduce the use of global
variables.
When we have few functions in our code, closures prove to be
efficient way. But if we need to have many functions, then go for
class (OOP).
Example for Closure
Advantages

• Allows you to avoid confusing problems and errors in the code


• Easier to test and execute Unit testing and debug FP Code.
• Parallel processing and concurrency
• Hot code deployment and fault tolerance
• Offers better modularity with a shorter code
• Increased productivity of the developer
• Supports Nested Functions
• Functional Constructs like Lazy Map & Lists, etc.
• Allows effective use of Lambda Calculus
Disadvantages

• Perhaps less efficiency


• Problems involving many variables or a lot of sequential
activity are sometimes easier to handle imperatively
• Functional programming paradigm is not easy, so it is
difficult to understand for the beginner
• Hard to maintain as many objects evolve during the
coding
• Needs lots of mocking and extensive environmental setup
• Re-use is very complicated and needs constantly
refactoring
• Objects may not represent the problem correctly
Transforming code from imperative to functional

1. Introduce higher-order functions.


2. Convert existing methods into pure functions.
3. Convert loops over to recursive/tail-recursive
methods (if possible).
4. Convert mutable variables into immutable
variables.
5. Use pattern matching (if possible).
Sample Scenario
1) (The MyTriangle module) Create a module named MyTriangle that contains the
following two functions:
# Returns true if the sum of any two sides is greater than the third side.
def isValid(side1, side2, side3):
# Returns the area of the triangle.
def area(side1, side2, side3):
Write a test program that reads three sides for a triangle and computes the area if the
input is valid. Otherwise, it displays that the input is invalid.

2) A prime number is called a Mersenne prime if it can be written in the form for some
positive integer p. Write a program that finds all Mersenne primes with and displays the
output as follows:
p 2^p - 1
2 3
3 7
5 31

62
Sample Scenarios

3) Write a function named ack that evaluates the Ackermann


function. Use your function to evaluate ack(3, 4), which should be
125.
Logic Programming Paradigm
Unit-IV (15 Session)
Session 1-3 cover the following topics:-
– Definition - S1-SLO1
– First-class function, Higher-order function, Pure functions, Recursion- S1-SLO2
– Packages: Kanren, SymPy – S2-SLO 1
– PySWIP, PyDatalog – S2-SLO 2
– Other languages: Prolog, ROOP, Janus S3-SLO 1
– Demo: Logic Programming in Python S3-SLO2

Lab 9: Logic Programming ( Case Study) ( S4-5)

Assignment : Comparative study of Logic programming in Prolog, ROOP, Janus

TextBook:

1) Shalom, Elad. A Review of Programming Paradigms Throughout the History: With a


Suggestion Toward a Future Approach, Kindle Edition
2) Amit Saha, Doing Math with Python: Use Programming to Explore Algebra,
Statistics,Calculus and More, Kindle Edition, 2015
Introduction

• It can be an abstract model of computation.


• Solve logical problems like puzzles, series
• Have knowledge base which we know before and along with
the question
• Knowledge is given to machine to produce result. Exp : AL
and ML code
Introductions

• The Logical Paradigm takes a declarative approach to


problem-solving.
• Various logical assertions about a situation are made,
establishing all known facts.
• Then queries are made.
• The role of the computer becomes maintaining data and logical
deduction.

• Exp : Prolog, ROOP, Janus


Features of Logical paradigms

• Computing takes place over the domain of all terms defined


over a “universal” alphabet.
• Values are assigned to variables by means of automatically
generated substitutions, called most general unifiers.
• These values may contain variables, called logical variables.
• The control is provided by a single mechanism: automatic
backtracking.
Parts of Logical programming

1. A series of definitions/declarations that define the problem


domain
2. Statements of relevant facts
3. Statement of goals in the form of a query
Advantages

• The system solves the problem, so the programming steps


themselves are kept to a minimum;
• Proving the validity of a given program is simple.
Example
domains
being = symbol

predicates
animal(being) % all animals are beings
dog(being) % all dogs are beings
die(being) % all beings die

clauses
animal(X) :- dog(X) % all dogs are animals
dog(fido). % fido is a dog
die(X) :- animal(X) % all animals die
SymPy Overview
• Simplification
– simplify
– Polynomial/Rational Function
Simplification
– Trigonometric Simplification
– Powers Reference:
– Exponentials and logarithms
– Special Functions • https://www.geeksforgeeks.org/pyth
– Example: Continued Fractions on-getting-started-with-sympy-
• Calculus
– Derivatives module/
– Integrals
– Limits
• https://docs.sympy.org/latest/tutoria
– Series Expansion l/index.html
– Finite differences
• Solvers
– A Note about Equations
– Solving Equations Algebraically
– Solving Differential Equations
• Matrices
– Basic Operations
– Basic Methods
– Matrix Constructors
– Advanced Methods
– Possible Issues
Scenario Questions

1) Suppose you are given the below string


str = “””Email_Address,Nickname,Group_Status,Join_Year
aa@aaa.com,aa,Owner,2014
bb@bbb.com,bb,Member,2015
cc@ccc.com,cc,Member,2017
dd@ddd.com,dd,Member,2016
ee@eee.com,ee,Member,2020 “””
• In order to extract only the domain names from the email
addresses from the above string (for eg. “aaa”, “bbb”..)
Dependent Types Paradigms
Unit-IV (15 Session)
Session 6-10 cover the following topics:-
– Dependent Type Programming Paradigm- S6-SLO1
– Logic Quantifier: for all, there exists- S6-SLO2
– Dependent functions, dependent pairs– S7-SLO 1
– Relation between data and its computation– S7-SLO 2
– Other Languages: Idris, Agda, Coq S8-SLO 1
– Demo: Dependent Type Programming in Python S8-SLO2

Lab 11: Dependent Programming ( Case Study) ( S8)


Assignment : Comparative study of Dependent programming in Idris, Agda, Coq

TextBook:

1) Amit Saha, Doing Math with Python: Use Programming to Explore Algebra,
Statistics,Calculus and More, Kindle Edition, 2015
URL :
• https://tech.peoplefund.co.kr/2018/11/28/programming-paradigm-and-python-
eng.html

• https://freecontent.manning.com/a-first-example-of-dependent-data-types/
Introductions

• In computer science and logic, a dependent type is a type


whose definition depends on a value.
• It is an overlapping feature of type theory and type systems.
• Used to encode logic's quantifiers like "for all" and "there
exists".
• Exp: Agda, ATS, Coq, F*, Epigram, and Idris
Examples of dependent types

• Dependent functions
– The return type of a dependent function may depend on
the value (not just type) of one of its arguments
• Dependent pairs
– A dependent pair may have a second value of which the
type depends on the first value
Network Programming Paradigm
Unit-IV (15 Session)
Session 11-15 cover the following topics:-
– Network Programming Paradigm - S11-SLO1
– Socket Programming: TCP & UDP Connection oriented, connectionless – S11-SLO2
– Sock_Stream, Sock_Dgram, socket(),bind(), recvfrom(), sendto(), listen()– S12-SLO 1
– Server-Client; send(), recv(), connect(),accept(), read(), write(), close()– S12-SLO 2
– Other languages: PowerShell, Bash, TCL S13-SLO 1
– Demo: Socket Programming in Python S13-SLO2

Lab 9: Socket Programming ( Case Study) ( S14-15)

Assignment : Comparative study of Socket programming in PowerShell, Bash,


TCL

TextBook:

1) John Goerzen, Brandon Rhodes, Foundations of Python Network Programming:


The comprehensive guide to building network applications with Python, 2nd ed.,
Kindle Edition, 2010
Introduction

• A socket is the most vital and fundamental entity


• Sockets are the end-point of a two-way communication link.
• An endpoint is a combination of IP address and the port number.
• For Client-Server communication,
– Sockets are to be configured at the two ends to initiate a
connection,
– Listen for incoming messages
– Send the responses at both ends
– Establishing a bidirectional communication.
Definition

• Sockets allow communication between processes that lie on


the same machine, or on different machines working in diverse
environment and even across different continents.
Create A Socket Object In Python
• sock_obj = socket.socket( socket_family, socket_type, protocol=0)

• socket_family: - Defines family of protocols used as transport mechanism.


– Either AF_UNIX, or
– AF_INET (IP version 4 or IPv4).

• socket_type: Defines the types of communication between the two end-points.


– SOCK_STREAM (for connection-oriented protocols, e.g., TCP), or
– SOCK_DGRAM (for connectionless protocols e.g. UDP).

• protocol: We typically leave this field or set this field to zero.


Example
#Managing errors in python socket programming
import socket #for sockets
import sys #for exit
try:
#create an AF_INET, STREAM socket (TCP)
sock_obj = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as err_msg:
print ('Unable to instantiate socket. Error code: ' + str(err_msg[0]) + ' ,
Error message : ' + err_msg[1])
sys.exit();
print ('Socket Initialized')
Types Of Socket Methods In Python’s Socket
Library

• Server Socket Methods,


• Client Socket Methods, and
• General Socket Methods.
Server Socket Methods
• sock_object.bind(address):
– binds the socket to address (hostname, port number pair)
• sock_object.listen(backlog):
– listen to the connections associated with the socket.
– Backlog parameter indicates maximum number of queued connections.
– Maximum value is up to 5, and minimum should be at least zero.
• sock_object.accept():
– This function returns (conn, address) pair where ‘conn’ is new socket
object used to send and receive data on the communication channel, and
‘address’ is the IP address tied to the socket on another end of the
channel.
– The ACCEPT() method returns a socket object which is different from
the socket object created using socket.socket().
– This new socket object is dedicatedly used to manage the communication
with the particular client with which accept happened.
– This mechanism also helps Server to maintain the connection with n
number of clients simultaneously.
Client Socket Methods

• sock_object.connect():
– This method is used to connect the client to host and port
– Initiate the connection towards the server.
General Socket Methods

• sock_object.recv():
– Use this method to receive messages at endpoints when the value of the protocol
parameter is TCP.
• sock_object.send():
– Apply this method to send messages from endpoints in case the protocol is TCP.
• sock_object.recvfrom():
– Call this method to receive messages at endpoints if the protocol used is UDP.
• sock_object.sendto():
– Invoke this method to send messages from endpoints if the protocol parameter is
UDP.
• sock_object.gethostname():
– This method returns hostname.
• sock_object.close():
– This method is used to close the socket. The remote endpoint will not receive
data from this side.
Python Socket Programming WorkFlow
Reference
• [T1] Elad Shalom, A Review of Programming Paradigms throughout the
History: With a suggestion Toward a Future
Approach, Kindle Edition, 2018

• [T2]John Goerzen, Brandon Rhodes, Foundations of Python Network


Programming: The comprehensive guide to building network applications with
Python, 2nd ed., Kindle Edition, 2010

• https://www.dataquest.io/blog/introduction-functional-programming-python/

• https://tech.peoplefund.co.kr/2018/11/28/programming-paradigm-and-python-
eng.html

• https://freecontent.manning.com/a-first-example-of-dependent-data-
types/
• https://www.guru99.com/functional-programming-tutorial.html#1
Thank you

You might also like