Professional Documents
Culture Documents
Introduction To Python & Network Programming in Python
Introduction To Python & Network Programming in Python
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
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
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
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
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
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.
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
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
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.
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
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
69
The End
70