Introduction to Python Network Programming Kansas State University

  • Slides: 24
Download presentation
Introduction to Python Network Programming Kansas State University at Salina

Introduction to Python Network Programming Kansas State University at Salina

Python Features Interpreted – platform independent, very high level, rapid development cycle Very clear

Python Features Interpreted – platform independent, very high level, rapid development cycle Very clear syntax – easy to learn, even just by example Fully Object Oriented, but not mandated No need to initialize variables Advanced built-in data structures allows for rapid development.

Basic Commands Indentation and block-structure Use colon and indention to identify a code block.

Basic Commands Indentation and block-structure Use colon and indention to identify a code block. n = 9 r = 1 while r n print n > 0: = r * n = n – 1 r Note: no need for semicolons or brackets

Strings Initialize strings with pairs of single quotes, double quotes, or triple quotes. a

Strings Initialize strings with pairs of single quotes, double quotes, or triple quotes. a = 't this starts with a "tab". ' b = "this string has 'line feed'. n" c = "backslash "quotes". " d = 'same for 'single' quotes. ' e = """The triple quote is nice for strings that take multiple lines. 'single' and "double" quotes do not need backslashes. """ Merging variables with strings: st = "There are %d lines and %d characters in the file" % (chars, lines)

Lists Very flexible built-in data container Like an array, a list contains "list" or

Lists Very flexible built-in data container Like an array, a list contains "list" or sequence of data. A list can contain a mixture of data types including any number type, strings, tuples, lists, dictionaries, functions, objects of any type. Mixture of data types allows easy creation of data structures.

Lists (continued) List Slicing: >>> x = ['first', 'second', 'third', 'forth'] >>> print x

Lists (continued) List Slicing: >>> x = ['first', 'second', 'third', 'forth'] >>> print x ['first', 'second', 'third', 'forth'] >>> x[2] 'third' >>> x[2: ] ['third', 'forth'] >>> x[: 2] ['first', 'second'] >>> x[1: 3] ['second', 'third'] >>> len(x) 4 Built-in functions operating on lists: in, +, *, del List methods: append, count, extend, index, insert, pop, remove, reverse, sort

Lists (continued) Built-in functions operating on lists: in, +, *, del >>> x =

Lists (continued) Built-in functions operating on lists: in, +, *, del >>> x = ['one', 'two', 'three', 'four'] >>> x ['one', 'two', 'three', 'four']. . . >>> for a in x: print a one two three four. . . >>> y = [5, 6] >>> print x + y ['one', 'two', 'three', 'four', 5, 6]. . . >>> print x * 2 ['one', 'two', 'three', 'four', 'one', 'two', 'three', 'four']. . . >>> del x[2] >>> print x ['one', 'two', 'four']

Lists (continued) List methods: append, count, extend, index, insert, pop, remove, reverse, sort >>>

Lists (continued) List methods: append, count, extend, index, insert, pop, remove, reverse, sort >>> print x ['one', 'two', 'four'] >>> x. insert(2, 'three'); print x ['one', 'two', 'three', 'four'] >>> x. append(['five', 'six']); print x ['one', 'two', 'three', 'four', ['five', 'six']]. . . >>> x. extend(['five', 'six']); print x ['one', 'two', 'three', 'four', 'five', 'six'] >>> x. count('four') 1 >>> x. index('five') 4 >>> x. pop() 'six' >>> x ['one', 'two', 'three', 'four', 'five'] >>> x. remove('two'); print x ['one', 'three', 'four', 'five'] >>> x. reverse(); print x ['five', 'four', 'three', 'one'] >>> x. sort(); print x ['five', 'four', 'one', 'three']

Tuples A tuple is a list that is immutable (can not be changed once

Tuples A tuple is a list that is immutable (can not be changed once created). x = (1, 2, 3) Use tuples when possible because they are more efficient than lists. Operators and built-in functions (in, +, *, len, min, max) may be used with tuples. Often used to allow multiple values returned from a function. x, y = function( … )

Tuples in Functions >>> def assign. Variables(a, b): c = a d = b

Tuples in Functions >>> def assign. Variables(a, b): c = a d = b return c, d >>> x, y = assign. Variables(2, 4) >>> x 2 >>> y 4

Dictionaries A list of two item pairs (key, value). The key is immutable. The

Dictionaries A list of two item pairs (key, value). The key is immutable. The value may be any object. Provides an associative array functionality implemented using hash tables. Built-in functions: len, del Dictionary methods: clear, copy, get, has_key, items, keys, update, values

Dictionary examples >>> d = {'one': 1, 'two': 2} >>> d['one'] 1 >>> d['one']

Dictionary examples >>> d = {'one': 1, 'two': 2} >>> d['one'] 1 >>> d['one'] = 3 >>> d['one'] 3 >>> d {'two': 2, 'one': 3} >>> d. items() [('two', 2), ('one', 3)] >>> d. keys() ['two', 'one'] >>> d. values() [2, 3] >>> d. has_key('two') True

Dictionary examples >>> d = >>> e = {'two': >>> f = {'two': {'one':

Dictionary examples >>> d = >>> e = {'two': >>> f = {'two': {'one': 1, 'two': 2} d. copy(); print e 2, 'one': 1} d; print f 2, 'one': 1} >>> d. update({'three': 3}) >>> print d {'three': 3, 'two': 2, 'one': 1} >>> print e {'two': 2, 'one': 1} >>> print f {'three': 3, 'two': 2, 'one': 1}

The 'for' loop >>> x = [ 1, 2, 3 ] >>> for i

The 'for' loop >>> x = [ 1, 2, 3 ] >>> for i in x: print i 1 2 3 >>> range(5) [0, 1, 2, 3, 4] >>> range(0, 6, 2) [0, 2, 4] >>> range(2, 6) [2, 3, 4, 5]

Basic I/O – printing Two ways of displaying text: >>> import sys >>> for

Basic I/O – printing Two ways of displaying text: >>> import sys >>> for i in range(3): sys. stdout. write("Hi ") Hi Hi Hi >>> for i in range(3): print("Hi") Hi Hi Hi

Basic I/O – reading data >>> x = input("Enter a number: ") Enter a

Basic I/O – reading data >>> x = input("Enter a number: ") Enter a number: 5 >>> x 5 >>> name = input("Enter your name: ") Enter your name: Tim Traceback (most recent call last): File "<pyshell#47>", line 1, . . . Name. Error: name 'Tim' is not defined >>> name = input("Enter your name: ") Enter your name: 'Tim' >>> name = raw_input("Enter your name: ") Enter your name: Tim >>> name 'Tim' >>> x = raw_input("Enter a number: ") Enter a number: 3 >>> x '3'

File I/O – reading a text file Reading a text file: >>> fileobj =

File I/O – reading a text file Reading a text file: >>> fileobj = open( "foo. txt", 'r' ) >>> lines = fileobj. readlines() >>> lines ['Test filen', 'line twon', 'line three'] >>> fileobj. close() A line at a time: import sys fileobj = open("foo. txt", 'r' ) lines = [] # an empty list while 1: line = fileobj. readline() if line == "": break lines. append(line) for l in lines: sys. stdout. write(l) sys. stdout. write('n') fileobj. close()

File I/O – Writing a fileobject = open("bar", 'w' ) fileobject. write("Hello, Worldn") fileobject.

File I/O – Writing a fileobject = open("bar", 'w' ) fileobject. write("Hello, Worldn") fileobject. close()

File I/O – Pickle your data >>> d = {'one': 1, 'two': 2, 'three':

File I/O – Pickle your data >>> d = {'one': 1, 'two': 2, 'three': 3 } >>> d {'three': 3, 'two': 2, 'one': 1} >>> >>> import c. Pickle file = open("dpickle", 'w') c. Pickle. dump(d, file) file. close() >>> fo = open("dpickle", 'r') >>> newd = c. Pickle. load(fo) >>> fo. close() >>> newd {'one': 1, 'three': 3, 'two': 2}

Functions Call by value or reference is the same as Java… >>> def test(x):

Functions Call by value or reference is the same as Java… >>> def test(x): x=x+2 >>> z = 2 >>> test(z) >>> print z 2 >>> def stest(st): st = st + "Hello" >>> s = "joe" >>> stest(s) >>> print s joe >>> class ctest: def __init__(self, n): self. n = n >>> def c 1 test(n): n. n = n. n + 2 >>> x = ctest(5) >>> x. n 5 >>> c 1 test(x) >>> x. n 7

Classes Syntax Class classname(base_class): “optional documentation string” static variable declarations method declarations Method declarations

Classes Syntax Class classname(base_class): “optional documentation string” static variable declarations method declarations Method declarations are just function definitions. The __init__(self, other_args) method is initialization code, not a constructor. Use the self. var_name to reference any class data variables.

Modules Allow for code reuse Provide a tool for grouping system components Allow components

Modules Allow for code reuse Provide a tool for grouping system components Allow components to be shared across multiple functions import <module>: executes all code in a module from <module> import <name>: executes specific code within a module Latter results in a more efficient program if only certain functions and attributes of a module are needed, since only the necessary code from the module is run

Exceptions Handled through the use of try [except else finally] blocks import sys try:

Exceptions Handled through the use of try [except else finally] blocks import sys try: file = open('no. File', 'r') except IOError: print 'File does not exist. ' sys. exit(1) else: print 'File exists. ' file. close() else block executes only if no exceptions are thrown, while finally block always executes

A word about the text book examples Examples assume that you are using some

A word about the text book examples Examples assume that you are using some form of Unix. They still work in Windows! #!/usr/bin/env python – Tells Unix which interpreter to use. It is ignored as a comment in windows. In Windows, either use Idle or invoke the interpreter explicitly from command prompt. Command line arguments work. The following program just prints argv[1]. C: . . Net. Programming>c: Python 25python argv. py help