1 / 24

Introduction to Python

Network Programming Kansas State University at Salina. Introduction to Python. 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

katen
Download Presentation

Introduction to Python

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Network Programming Kansas State University at Salina Introduction to Python

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

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

  4. Strings Initialize strings with pairs of single quotes, double quotes, or triple quotes. Merging variables with strings: 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.""" st = "There are %d lines and %d characters \ in the file" % (chars, lines)

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

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

  7. 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']

  8. 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']

  9. 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( … )

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

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

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

  13. Dictionary examples >>> d = {'one':1, 'two':2} >>> e = d.copy(); print e {'two': 2, 'one': 1} >>> f = d; print f {'two': 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}

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

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

  16. 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, . . . NameError: name 'Tim' is not defined >>> name = input("Enter your name: ") Enter your name: 'Tim' >>> 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'

  17. File I/O – reading a text file Reading a text file: >>> fileobj = open( "foo.txt", 'r' ) >>> lines = fileobj.readlines() >>> lines ['Test file\n', 'line two\n', '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()

  18. File I/O – Writing a file fileobject = open("bar", 'w' ) fileobject.write("Hello, World\n") fileobject.close()

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

  20. 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 c1test(n): n.n = n.n + 2 >>> x = ctest(5) >>> x.n 5 >>> c1test(x) >>> x.n 7

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

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

  23. Exceptions Handled through the use of try [except else finally] blocks import systry: file = open('noFile', '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

  24. 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:\..\NetProgramming>c:\Python25\python argv.py help help

More Related