Introduction to Python

Introduction to Python

Introduction to Python GPS Resource Seminar Eh Tan Nov. 17, 2005 What is Python? • Python is a portable, interpreted, interactive, extensible, object-oriented programming language. o Portable: run on Linux, many types of Unix, Windows, Mac, OS/2, … Comment: Python is a standard package and Interpreted: no compiling and linking, fast edit-test-debug cycle is an administrative tool in many linux o distributions o Interactive: test while you code Comment: Development in python is 5-10x o Extensible: interface with C/C++ faster than in C/C++ • Often compared to Tcl, Perl, or Java. Comment: Forget the syntax? Unsure about • Clear and elegant syntax -- easy to learn and read the outcome of a function? Test it in the • Powerful -- suitable for all kinds of work interpreter o sourceforge.net language statistics: Comment: With simple wrappers, python . C++: 16544 projects can call C/C++ functions . Java: 16473 projects Comment: Readability of code is very important when maintaining your own or . C: 15772 projects other’s code . PHP: 11970 projects . Perl: 6155 projects . Python: 4457 projects . … . Fortran: 165 projects • Current version: 2.4 Comment: New features are added into python in every new version. If I am using any new features introduced after v2.3, I will put a remark. Features of Python • Automatic memory management • Strong and dynamic typing • High level data structures (list and dict) • Strong support for string operation (including regular expression) • Namespaces • Modular design • Supporting procedural, functional, and objected-oriented programming • Interfaces to system calls and libraries • Interfacces to various GUI systems (GTK, Qt, Motif, Tk, Mac, MFC, wxWidgets). When to use Python? • Almost every situation, except: o Simple script for running a batch of commands (use Shell script instead) o Serious number crunching (use Fortan, C instead). However, there are python extension modules that can give you the speed of C! . Take a look at SciPy (numeric.scipy.org) and ScientificPython (starship.python.net/~hinsen/ScientificPython) o Plotting and visualization (use Matlab, IDL, GMT instead) . matplotlib (matplotlib.sourceforge.net) . MayaVi (mayavi.sourceforge.net) . ParaView (www.paraview.org) Resources • Online resources o python interpreter online help >>> help(foo) Comment: '>>>' is the prompt of python (print out the documentation of foo) interpreter >>> dir(foo) (print out the methods of foo) o www.python.org/doc contains many links to tutorials, ebooks, and references. The python tutorial (docs.python.org/tut/tut.html) is the official tutorial (and is always up to date). o diveintopython.org has a good tutorial for experienced programmer (but new to python) • Books o Core Python Programming, W. Chun, Prentice Hall – good for beginner and advanced programmer (out of print) o Learning Python, M. Lutz and D. Ascher, O'Reilly & Associates – good beginner’s book o Python in a Nutshell, A. Martelli, O'Reilly & Associates – good for experienced programmers and as a language reference o Python Essential Reference, D. Beazley, New Riders – desktop reference Python Editors • Emacs or XEmacs with python-mode • Vi or Vim • Integrate Development Environment: IDLE, IPython, ActivePython Programming in Python • Case sensitive • # starts comment • Indentation matters if t > 0: Comment: Notice that there is no positive = True parenthesis around the condition and the “:” if verbose: after the condition and “else” print “t is positive” Comment: True and False are python else: constants positive = False Comment: This “else” follows the first “if” • Line continuation o Trailing backslash s = 1 + \ 2 o (…), […], {…} can span multiple lines s = (1 + 2) • No variable declaration • Use of undefined variable is an error • Variables are references (like C pointers) of objects Comment: Many C/Fortran programmers >>> a = b = 5 get confused at this point. Read the following >>> b = 4 example carefully. >>> print a, b Comment: a and b are both references of 5 5 4 Comment: b is changed to be a reference of >>> a = b = [1, 2] 4, but a is unchanged >>> b[0] = 0 >>> print a, b Comment: a and b are both references of a [0, 2] [0, 2] list (a list is like an array) Comment: The first element of the array is changed to 0 print Comment: Both a and b sees the change • Output to stdout >>> print 123 123 • Add new line character in the end (suppressed by a trailing comma) >>> for i in [1,2,3]: print i 1 2 3 >>> for i in [1,2,3]: print i, 1 2 3 • Add space between each element >>> print 1,2,3 1 2 3 • Redirection >>> print >> f, 123 Comment: f is a file/stream object (discussed later) Numbers • int o Decimal, octal, hexadecimal 12 == 014, 12 == 0xC o No limit on # of digits 10**100**2 o Conversion int(12.6), int(‘12’) Comment: float-to-int conversion is • float truncated, or rounded toward the floor. o Double precision Comment: There is no single-precision float 12.0, 1.2e1 in python. The only place you will need it is Conversion during I/O. In this case, use struct or array o modules (discussed later). float(12), float(‘1.2e1’) • complex o Append with ‘j’ 3+4j o Conversion complex(‘3+4j’), complex(3,4) • Operators: +, -, *, /, //, %, ** o Division >>> print 3 / 5 0 Comment: int/int returns int, rounded >>> print 3.0 / 5 toward the floor 0. 6 Comment: float/int or int/float returns float >>> print 3.0 // 5 0.0 Comment: // always returns “integer value” >>> from __future__ import division Comment: In future (python 3.0), true >>> print 3 / 5 division will become the default, and this line 0.6 will not be necessary >>> print 3.0 / 5 0.6 >>> print 3.0 // 5 0.0 str • Single or double quotes ‘abc’, “abc”, “I don’t”, ‘He said “No”’ • Triple-quotes for multi-line string ‘’’This is the first line the second the third’’’ • Conversion Comment: Every object, not just numbers, str(12), str(3.2) can be converted to string • Escape characters Comment: To print a float with specified >>> print ‘abc\ndef’ digits, see “String Formatting” section below. abc def >>> print ‘abc\’def’ abc’def >>> print ‘abc\\def’ abc\def • Operators: +, *, in >>> print ‘abc’ + ‘def’ abcdef >>> print ‘abc’*3 abcabcabc >>> print ‘a’ in ‘abc’ Comment: 'a' is a string of length 1. There is True no char type in python. str Methods • Query on the nature of characters: isspace(), isalpha(), isdigit(), isalnum() • Case manipulation: lower(), upper(), swapcase(), title() • Whitespace removal: strip(), lstrip(), rstrip(), split(), splitlines() • Justification: ljust(), rjust(), center(), zfill() • Search: count(), find(), rfind(), index(), rindex(), startswith(), endswith() • Search and replace: replace(), translate() • Joining a list of string: join() greeting = ‘Hello’ + ‘ ‘ + ‘Mr.’ + ‘ ‘ + ‘Tan’ greeting = ‘ ‘.join([‘Hello’, ‘Mr.’, ‘Tan’]) Comment: Both methods give the same result, but the 2nd method is faster. list • [elem1, …] • Useful function: range() >>> print range(3) Comment: Integers between [0, 3) [0, 1, 2] >>> print range(1,3) Comment: Integers between [1, 3) [1, 2] >>> print range(1,6,2) Comment: Integers between [1, 6) with [1, 3, 5] stride 2 • Like a C array, but can contain different types of elements >>> alist = [1, 3.5, ‘a’, [1,2,3]] • Access by index, index starts from 0 >>> print alist[2] ‘a’ • Negative index >>> print alist[-1] Comment: The last element. Think of alist[- [1, 2, 3] 1] == alist[n-1], where n = len(alist) >>> print alist[-2] ‘a’ • Index slice >>> print alist[0:2] Comment: [0, 2) [1, 3.5] >>> print alist[::2] Comment: [0, len(alist)) with stride=2 [1, ‘a’] >>> print alist[-2:] Comment: The last 2 elements. [n-2, n), [‘a’, [1, 2, 3]] n=len(alist) • Operators: +, *, in, del >>> del alist[0] >>> print alist [3.5, ‘a’, [1, 2, 3]] list Comprehension • A convenient way to generate a list • For example, a list of even integer that is less than 10, in math formula: s = { x | x ∈ [0, 1, 2, …, 9], (x%2) == 0 } Similarly, in python: s = [ x for x in range(10) if (x%2) == 0 ] • Another example, a list of numbers that is the square root of all less-than-10 integers, and converts each number to string s = [ str(sqrt(x)) for x in range(10) ] Comment: Need to import math module to call sqrt() (discussed later) list Methods • Add element: append(), insert(), extend() • Remove element: remove(), pop() • Search: count(), index() • Sort: reverse(), sort() tuple • (elem1, …) • Single-element tuple >>> print (1) Comment: This creates an integer 1, not a 1 tuple. The () are interpreted as arithmatic >>> print (1,) grouping. (1,) Comment: The trailing comma indicates we • Similar to list, but immutable want a single-element tuple >>> atuple = (1, 2, ‘a’) Comment: String can be consider as a >>> print atuple[1] special case of tuple, which contains characters 1 only. String, list, and tuple are typical sequence >>> atuple[2] = 3 object. Traceback (most recent call last): File "<stdin>", line 1, in ? Comment: This line shows the location of TypeError: object does not support item assignment the error • Tuple unpacking Comment: This line shows the category of >>> a, b, c = (1, 2, 3) the error and a detailed error message >>> print a, b, c 1 2 3 • Operators: +, *, in dict • {key1: value1, …} • Access by key, like map in C++ or associative array in Perl >>> adict = { ‘name’: ‘Eh’ ‘office’: ‘358 SM’ } >>> print addict[‘name’] Eh • Elements are not ordered, cannot access by index • Operators: in, del >>> print ‘name’ in adict True >>> print ‘Eh’ in adict Comment: ‘in’ operator checks the key, not False the value of the dict >>> del adict[‘name’] >>> print adict {‘office’: ‘358 SM’} dict

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    15 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us