Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 70

Introduction to Python &

Network Programming in Python


Outline
Object
Types &
Introduction Reference &
Operations
Object

Object-
Control Flow
Functions Oriented
Statements
Programming

Network
Programming
with Python 2
Introduction
3
What is Python?
• An object-oriented scripting language
• Developed by Guido van Rossum in the early 1990s
• Named after Monty Python (comedy series)
• Available for download from http://www.python.org

4
Why Python?
• Easy to use, easy to read, easy to write
• Portable
• Powerful
dynamic typing, auto memory management, buit-in object types,
buit-in tools, library utilities, 3rd-party utilities
• Mixable
can be “glued” to components written in other languages
• Free

5
How to use Python?
Using the Interactive Prompt
• Type “python” at system shell prompt to begin an
interactive Python session and then run the code:
$ python
>>> print(‘Hello world!’) # Python 3
>>> print ‘Hello world!’ # Python 2.6
Hello world!
>>> 2 ** 8
256
•  Perfect place for experiment with the language or to
test code

6
How to use Python?
Creating & Running Script Files
• Write using any editor (gedit)
#!/usr/bin/env python
print("Hello", "World!") # Python 3
print ‘Hello’, “World!” # Python 2.6
• Save it
hello.py
• Execute
$ chmod +x hello.py
$ ./hello.py
Or
$ python hello.py
7
• Route output to a file:
$ python hello.py > output.txt
Object Reference &
Object
8
Object Reference & Object
Python Other languages
Object references Variables
Object Data

• Similar to pointer in C
• Syntax: object_reference = value
x = "blue"
y = "green"
z=x
• x = "blue“ : str object created with the text “blue”; object
reference x created, set to bind to the str object
• z = x : new object reference z created, set to bind the same
object that x binds to 9
Object Reference & Object
• Built-in object types a.k.a. core data types
Object type Example generation
Numbers 1234, 3.1415, 3+4j, Decimal, Fraction
Strings 'spam', "guido's", b'a\x01c'
Lists [1, [2, 'three'], 4]
Dictionaries {'food': 'spam', 'taste': 'yum'}
Tuples (1, 'spam', 4, 'U')
Files myfile = open('eggs', 'r')
Sets set('abc'), {'a', 'b', 'c'}
Other core types Booleans, types, None
Program unit types Functions, modules, classes
10
Object Reference & Object
• Numbers (intergers, floating-point numbers, complex numbers
and fractions), string, tuples and sets are immutable.
• However, we can change the value of a variable (i.e. object
reference) by changing the object that it refers to.
• Example:
>>> x = 3
>>> x = x + 1
>>> print x
4

11
Object Reference & Object
What really happens is: >>> x = x + 1
1. The object that x refers to is looked up.
2. The value of that object is retrieved.

Type: Integer
Data: 3
Name: x
Ref: <address1>
12
Object Reference & Object
What really happens is: >>> x = x + 1
1. The object that x refers to is looked up.
2. The value of that object is retrieved.
3. The 3 + 1 calculation occurs, producing a new value 4 which
is stored in a new object. That object is then assigned to a
fresh memory location.

Type: Integer
Data: 3
Name: x
Ref: <address1>
Type: Integer 13
Data: 4
Object Reference & Object
What really happens is: >>> x = x + 1
1. The object that x refers to is looked up.
2. The value of that object is retrieved.
3. The 3 + 1 calculation occurs, producing a new value 4 which
is stored in a new object. That object is then assigned to a
fresh memory location.
4. x is changed to refer to this new object.
5. The old object is garbage collected if no object reference
points to it.
Type: Integer
Data: 3
Name: x
Ref: <address1>
Type: Integer 14
Data: 4
Types & Operations

15
Logical Expressions
• Relational operators
Relational operator Meaning
== equals
!= does not equal
< less than
> greater than
<= less than or equal to
>= greater than or equal to

Chained comparison is available: x < y < z


• Logical operators
Operator Example Result
and 9 != 6 and 2 < 3 True
2 and 5 2
or 2 == 3 or -1 < 5 True
2 or 5 5 16
not not 7 > 0 False
Numbers
• Numeric Operators: +, -, *, / (float in 3.0, int in 2.6), // (int), %,
** (exponentiation)
• Math Functions: abs(x), divmod(x, y), pow(x), round(x, n),
bin(i), hex(i), int(x), int(s, base), oct(i)
• Bitwise Conversion:
Syntax Description
i|j Bitwise OR
i^j Bitwise XOR
i&j Bitwise AND
i << j Shift i left by j bits
i >> j Shift i right by j bits
-i Invert’s i bits 17
Sequences
1. Strings
• Ordered collections of characters
• Immutable
• Defined using quotes (‘, ‘’ and “”” for multi-line)
2. Lists
• Ordered collections of objects of mixed types
• Mutable
• Defined using square brackets
3. Tuples:
• Ordered collections of objects of mixed types
• Immutable
18
• Defined using parentheses
Sequences: Examples
• >>> myString = ‘Hello World’
• >>> myString = “matt’s”
• >>> myString = “““This is a multi-line
string that uses triple quotes.”””
• >>> myString = “””a’b’’c”””

• >>> myList = [“abc”, 34, 4.34, 23]

• >>> myTuple = (23, ‘abc’, 4.56, (2,3), ‘def’)

19
Sequences: Common Operations
• Apply to both string, list, tuples
1. Indexing expression
T[-5] T[-4] T[-3] T[-2] T[-1]
‘venus’ -28 ‘green’ ’21’ 19.74
T[0] T[1] T[2] T[3] T[4]
2. Slide
>>> S  'Spam'
>>> S[1:3]  ‘pa'
>>> S[1:]  'pam'
>>> S[:3]  'Spa'
>>> S[:-1]  'Spa‘
>>> S[:]  'Spam’ 20
>>> S[1:4:2]  ‘pm’
Sequences: Common Operations
3. Size function
>>> S = 'Spam'
>>> len(S)  4
4. Concatenation
>>> S + ‘xyz’  ‘Spamxyz’
5. Repetition
>>> S * 8  'SpamSpamSpamSpamSpamSpamSpamSpam‘
6. Membership testing
>>> 3 in [1, 2, 4, 5]  False
>>> 3 not in [1, 2, 4, 5]  True
For string, we can check either a character or a substring is
in/not in a string
7. Sorting 21
>>> sorted((5, 1, 4, 3))  [1, 3, 4, 5]
Sequences: String
1. String conversion
>>> int("42"), str(42)  (42, ’42’)
2. Character code conversion
>>> ord(‘s’), chr(115)  (115, ‘s’)
3. String formating expression
>>> That is %d %s bird!' % (1, 'dead')
>>> 'That is {0} {1} bird!'.format(1, 'dead') # v2.6 & v3.0
 'That is 1 dead bird!‘

22
Sequences: String
4. Typical methods
Syntax Description
s.upper(), s.lower() Return uppercased/lowercased copy of s
s.find(t, start, end) Return leftmost position of t in the start:end slide of s or -1 if not
found
s.replace(t, u, n) Return a copy of s with n occurrences of str t replaced with str u
s.join(seq) Return the concatenation of every item in the sequence
seq, with str s (which may be empty) between each one
s.split(t, n) Return a list of strings splitting at most n times on str t
s.isdigit() Return True if s is nonempty and every character in s is
an ASCII digit
s.count(t, start, Return the number of occurrences of str t in the start:end slice
end) of s
(etc) 23
Sequences: Lists
1. Sequence unpacking
>>> first, *rest = [9, 2, -4, 8, 7]
>>> first, rest  (9, [2, -4, 8, 7])
>>> first, *mid, last = "Charles Philip George Windsor".split()
>>> first, mid, last  ('Charles', ['Philip', 'George'], 'Windsor')
2. Starred expression
Ex: create function product that requires 3 arguments:
>>> product(2, 3, 5)  30
>>> L = [2, 3, 5]
>>> product(*L)  30
>>> product(2, *L[1:])  30

24
Sequences: Lists
3. Methods
Syntax Return value
L.append(x) Appends item x to the end of list L
L.count(x) Returns the number of times item x occurs in list L
L.extend(m), L+=m Appends all of iterable m’s items to the end of list L
L.index(x, start, end) Returns leftmost position of item x in the start:end
slice of L; or raises a ValueError exception if not found
L.insert(i, x) Inserts item x into list L at position int I
L.pop() Returns and removes the rightmost item of list L
L.pop(i) Returns and removes the item at position int i in L
L.remove(x) Removes the leftmost occurrence of item x from list
L,or raises a ValueError exception if x is not found
L.reverse() Reverses list L in-place 25
L.sort(...) Sorts list L in-place
Sequences: Tuples
1. Conversion
>>> L = list(T) # Make a list from a tuple's items
>>> T= tuple(L) # Make a tuple from the list's items
2. Methods

Syntax Return value


T.index(x) Return the offset of first occurrence of item x
T.index(x, n) Return the offset of occurrence of item x after offset n
T.count(x) Return the number of occurrence of item x

26
Dictionaries
• Accessed by key (immutable types), not offset
• Unordered collections of key-value pairs where values are
objects of mixed types
• Mutable
• Defined using curly brackets:
>>> d = {‘user’: ‘root’, ‘pswd’: ‘1234’}

27
Dictionaries
1. Fetch a value by key
>>> d[‘user’]  ‘root’
2. Change entry
>>>d[‘user’] = [‘root’, ‘hung’]
>>> d  {‘user’: [’root’, ‘hung’], ‘pswd’: ’1234’}
3. Delete entry
>>> del d[‘pswd’]
>>> d  {‘user’: [’root’, ‘hung’]}
4. Add entry
>>> d[‘level’] = 1
>>> d  {‘user’: [’root’, ‘hung’], ‘level’: 1}
28
Dictionaries
5. Typical methods
Syntax Description
d.clear() Removes all items from dict d
d.copy() Returns a shallow copy of dict d
d.get(k, v) Returns key k’s associated value, or v if k isn’t in dict d
d.pop(k, v) Returns key k’s associated value and removes the item, or
returns v if not found
d.update(a) Adds every (key, value) pair from a that isn’t in dict d to d,
and replace the value of key that already exist in d with
the new one from a
d.keys() Returns a dictionary view of all the keys in dict d
d.values() Returns a dictionary view of all the values in dict d
(etc) 29
Files Handling
Operation Interpretation
output = open(‘output.txt', 'w') Create output file ('w' means write)
input = open(‘input.txt', 'r') Create input file ('r' means read)
input = open(‘input.txt') Same as prior line ('r' is the default)
aString = input.read() Read entire file into a single string
aString = input.read(N) Read up to next N characters (or
bytes) into a string
aString = input.readline() Read next line (including \n
newline) into a string
aList = input.readlines() Read entire file into list of line
strings (with \n)
for line in open(‘data.dat'): use line File iterators read line by line

30
Files Handling
Operation Interpretation
output.write(aString) Write a string of characters (or bytes)
into file
output.writelines(aList) Write all line strings in a list into file
output.close() Manual close (done for you when file is
collected) - Optional
output.flush() Flush output buffer to disk without
closing
anyFile.seek(N) Change file position to offset N for next
operation
open('f.txt', encoding='latin-1') Python 3.0 Unicode text files (str
strings)
open('f.bin', 'rb') Python 3.0 binary bytes files (bytes
strings)
31
Control Flow
Statements
if Conditional Statement
if boolean_expression1:
suite1
elif boolean_expression2:
suite2
...
elif boolean_expressionN:
suiteN
else:
else_suite
Note:
• Colon (:) are used where the suite (block of code) is to follow
• Suite are indicated using indentation (four spaces, no tabs for each
level) 33
while Loop Statement
while True:
item = get_next_item()
if not item:
break
process_item(item)

34
for Loop Statement
for variable in iterable:
suite

• range(x) function returns a list of numbers from 0 to the


number before x.
range(5) returns [0,1,2,3,4]
for x in range(5):
print x

35
break, continue, pass & Loop else
• break
Jumps out of the closest enclosing loop (past the entire loop
statement)
• continue
Jumps to the top of the closest enclosing loop (to the loop’s
header line)
• pass
Does nothing at all: it’s an empty statement placeholder
• Loop else block
Runs if and only if the loop is exited normally (i.e., without hitting
a break)

36
Functions
Functions Definition
x=5
y=3
z=5

# arg2 and arg3 are optional,


# they have default values if one is not passed.
def function_name(arg1, arg2 = default_value2, arg3 = default_value3):
global x
print x # This will print 5
x = 3 # This will change the global
print y # This will print 3
print z # This will raise an exception as z is bound
# to a new local object
z=3
return x, y, z # This will return a tuple to contain multiple values 38

retTuple = function_name(1, 2)`


Functions Definition
• Parameters are passed-by-assignment
 Immutable arguments are passed-by-value
 Mutable arguments are passed-by-reference
• Lambda functions: comprised of a single statement. 
functionvar = lambda x: x + 1
# Same as def f(x): return x + 1
• Functions are first-class objects in Python
 Used as any other data type: arguments to function,
assigned to variables, parts of tuples, lists, etc
 Allow arbitrary attributes to be attached to record info for
later use
func.attr = value 39
Object-Oriented Programming:
Class & Methods

40
Class Definition
• A class is a special data type which defines how to build a
certain kind of object.
• The class also stores some data items that are shared by all
the instances of this class.
• Instances are objects that are created which follow the
definition given inside of the class.
• Python doesn’t use separate class interface definitions as in
some languages. You just define the class and then use it.

41
Methods in a Class
• Define a method in a class by including function definitions
within the scope of the class block.
• There must be a special first argument self in all method
definitions which gets bound to the calling instance
• There is usually a special method called __init__ in most
classes
• We’ll talk about both later…

42
A simple class definition:
student

class student: #A class representing a student.


def __init__(self,n,a):
self.full_name = n
self.age = a
def get_age(self):
return self.age

43
Objects Instantiation
• There is no “new” keyword as in Java.
• Merely use the class name with () notation and assign the
result to a variable.
• __init__ serves as a constructor for the class. Usually does
some initialization work.
• The arguments passed to the class name are given to its
__init__() method.
• So, the __init__ method for student is passed “Bob” and 21 here
and the new class instance is bound to b:
b = student(“Bob”, 21)

44
self Argument
• The first argument of every method is a reference to the current
instance of the class.
By convention, we name this argument self.
• In __init__, self refers to the object currently being created; so, in
other class methods, it refers to the instance whose method was
called.
 Similar to the keyword this in Java or C++.
 But Python uses self more often than Java uses this.

Defining a method: Calling a method:


(this code inside a class definition)
def set_age(self, num): >>> x.set_age(23)
self.age = num 45
Object-Oriented Programming:
Accessing Attributes & Methods

46
Definition of student
class student: # A class representing a student.
def __init__(self,n,a):
self.full_name = n
self.age = a
def get_age(self):
return self.age

>>> f = student (“Bob Smith”, 23)


>>> f.full_name # Access an attribute.
“Bob Smith”
>>> f.get_age() # Access a method.
23 47
Accessing unknown members :
getattr(object_instance, string)

>>> f = student(“Bob Smith”, 23)


>>> getattr(f, “full_name”)
“Bob Smith”
>>> getattr(f, “get_age”)
<method get_age of class studentClass at 010B3C2>
>>> getattr(f, “get_age”)() # We can call this.
23
>>> getattr(f, “get_birthday”)
# Raises AttributeError – No method exists.

48
Attributes
• The non-method data stored by objects.
• Data attributes
 Variable owned by a particular instance of a class.
 Each instance has its own value for it.
 These are the most common kind of attribute.
• Class attributes
 Owned by the class as a whole.
 All instances of the class share the same value for it.
 Called “static” variables in some languages.
 Good for
o class-wide constants
o building counter of how many instances of the class
have been made
49
Data Attributes
• Data attributes are created and initialized by an __init__()
method.
 Simply assigning to a name creates the attribute.
 Inside the class, refer to data attributes using self
o for example, self.full_name

class teacher: #A class representing teachers.


def __init__(self,n):
self.full_name = n
def print_name(self):
print self.full_name

50
Class Attributes
• Because all instances of a class share one copy of a class
attribute:
• when any instance changes it, the value is changed for all
instances.
• Class attributes are defined
• within a class definition
• outside of any method
• Since there is one of these attributes per class and not one per
instance, they are accessed using a different notation:
• Access class attributes using self.__class__.name notation.

class sample: >>> a = sample()


x = 23 >>> a.increment()
def increment(self): >>> a.__class__.x 51
self.__class__.x += 1 24
Data vs. Class Attributes

class counter: >>> a = counter()


overall_total = 0 >>> b = counter()
>>> a.increment()
# class attribute >>> b.increment()
def __init__(self): >>> b.increment()
self.my_total = 0 >>> a.my_total
# data attribute 1
def increment(self): >>> a.__class__.overall_total
3
counter.overall_total +=
>>> b.my_total
1
2
self.my_total += 1 >>> b.__class__.overall_total
3 52
Object-Oriented Programming:
Inheritance

53
Subclasses
• A class can extend the definition of another class
• Allows use (or extension) of methods and attributes already
defined in the previous one.
• New class: subclass. Original: parent, ancestor or superclass
• To define a subclass, put the name of the superclass in
parentheses after the subclass’s name on the first line of the
definition.
class ai_student(student):
• Python has no ‘extends’ keyword like Java.
• Multiple inheritance is supported.

54
Definition of a class extending student
class student: #A class representing a student.
def __init__(self,n,a):
self.full_name = n
self.age = a
def get_age(self):
return self.age

class ai_student(student): #A class extending student.


def __init__(self,n,a,s):
student.__init__(self,n,a) #Call __init__ for student
self.section_num = s
def get_age(): #Redefines get_age method entirely
print “Age: ” + str(self.age)
55
Network Programming with
Python

 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.
Network Programming with Python
• Import the Socket Module
import socket
• Creates Socket
anySocket = socket.socket(socket_family, socket_type, protocol = 0)
• Bind
serverSocket.bind(address, port)
• Listen
serverSocket.listen(numberConnection)
• Connect
clientSocket.connect(address,port)
• Accept connection
clientSocket, clientAddress = serverSocket.accept()
Network Programming with Python
• Send message
anySocket.send(string) # Transmit TCP message
anySocket.sendto(string, address) # Transmit UDP message
• Receive message
anySocket.recv(bufferSize) # Receive TCP message
anySocket.recvfrom(bufferSize)# Receive UDP message
• Close Socket
anySocket.close()
• Other methods
anySocket.gethostname() # Return the hostname
TCP Client - Server

59
60
61
UDP Client - Server

62
63
64
Multi-Thread Server

65
Multi-Thread Server
• Multi-Thread servers use a separate thread for handling each
connection. Threads are defined as light processes and are
running in and along with the main process which started
them.
• Shoud define function handler() to handle a simple connection
for each time client connect to server

66
Thread Server
import socket, thread
def handler(socket):
...
...

while 1:
clientSocket, clientAddress = sock.accept()
syslog.syslog('In coming connection')
thread.start_new_thread(handler, (clientSock,))

67
Python Internet Modules
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


68
References
• Python Homepage: http://www.python.org/
• Mark Lutz – Learning Python 4th edition
• Mark Summerfield - Programming in Python 3: A Complete
Introduction to the Python Language 2nd edition
• Norman Matloff - Tutorial on Network Programming with
Python

69
The End

70

You might also like