![]() |
![]() |
|
home—info—lectures—exams—hws—archive
A good tutorial at http://docs.python.org/tutorial/introduction.html
To run python on rucs: (a) ssh or putty into a rucs.radford.edu shell; (b) run/usr/bin/python (c) For batch processing, make a text file filename.py whose first line is#! /usr/bin/python , make sure the file is executable (chmod ugo+x filename.py) and then (from a UNIX prompt) just run it: filename.py.Values
Like scheme, variables aren't typed though values are. - None - numbers: Exact by default (well, internally uses C 'longs', and then gracefully overflows to 'L') import sys sys.maxint Use 'j' for complex: 3+2j x % y # mod x // y # quotient divmod(x,y) # returns a tuple; deprecated for complex. x ** y # exponent; also pow(x,y) pow(0,0) # ! convenience over safety? - strings in double *or* single-quotes; You can quote the newline in a string literal (gets discarded) here-strings: - adjacent string *literals* are auto-concated - + overloaded for addition and string-concat; * overloaded for mult. and string-copies 'str' generates human-readable versions of any value; 'repr' generates machine-readable verisons - charAt is implicit with [..]; slices: "hello"[:2] "hello"[2:] forall s forall i s == s[:i] + s[i:] This is even true out-of-range (however, charAt doesn't support that) Negative indices count from the right of the string (but beware -0). - "strip" is a method; "len" is a function - strings immutable, like Java, scheme - booleans: constants True, False a < b == c In scheme, 'and','or' can be applied to any values; anything non-false is true. In Python, 0 and '' and {} and [] are false; others are true: - lists -- very simalar to strings: stuff = [2, 'hi', [3,4], []] stuff[1] stuff[2:] - tuples: fixed-length, non-mutable; use parens. frog1 = (50,100, 'up') # 'define-values' de-structing tuples: (x,y,dir) = frog1 Note that the parens are optional [except for empty tuple () and for singleton use comma: 3, = (3,) - hash tables: { 'ian':17, 'fred':25, 'amy':2 } get/put via array [] notation for iterating, methods .keys(), .values constructor 'dict' will also accept list-of-2tuples: dict([(x, x**2) for x in (2, 4, 6)]) dict([(x, x**2) for x in (2, 4, 6)]) - variables, assignment multiple values allowed: a,b = 3,4 - sets Use the constructor 'set'. & union | intersect - diff ^ symm.diffin (works for lists too) - operators <, == generalized to tuples, lists etc; lexicographic. (1,3,5) < (2,11,7) # True (1,3,5) < (2,11,7,9) # True # comparing different types works, but all strings < any tuple, etc: (3, (4, 5)) < (3, 'hi') 3 < 'hi' 3 < (3,) - whitespace significant: a, b = 0, 1 while b < 1000: print b, a, b = b, a+b 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 - for(-each), map, filter, reduce are built-in: ssf = 0 for i in [3,4,5]: ssf = ssf + i print ssf import math; map( math.sqrt, [3,4,5,6] ) map( math.sqrt, range(100)) filter( lambda n: n%3 and n%2, range(100) ) reduce( +, 0, [3,4,5] ) // Error -- "+"; use lambda instead (argh) reduce( lambda a,b: a+b, [3,4,5] ) reduce( lambda a,b: a+b, [3,4,5], 0 ) reduce( lambda a,b: a+b, [3,4,5], 9 ) reduce( lambda a,b: a+b, ["hi","there","all"], "ahem" ) - keyword arguments # assoc, where `data` is a list-of-pairs. # ('course, in real python you'd use a dict to start with) # def assoc_default(key,data,default=None): asDict = dict(data) if key in asDict.keys(): # note that calling 'keys' is redundant return asDict[key] else: return default --varargs (incl. for keywords:) def cheeseshop(kind, *arguments, **keywords): print "-- Do you have any", kind, "?" print "-- I'm sorry, we're all out of", kind for arg in arguments: print arg print "-" * 40 keys = keywords.keys() keys.sort() for kw in keys: print kw, ":", keywords[kw] cheeseshop("Limburger", "It's very runny, sir.", "It's really very, VERY runny, sir.", shopkeeper='Michael Palin', client="John Cleese", sketch="Cheese Shop Sketch") - Do you have any Limburger ? -- I'm sorry, we're all out of Limburger It's very runny, sir. It's really very, VERY runny, sir. ---------------------------------------- client : John Cleese shopkeeper : Michael Palin sketch : Cheese Shop Sketch - apply: use * when making the *call*: def sumArgs( *x ): # in param position, the '*' means pack ssf = 0 for i in x: ssf = ssf + i return ssf def sumLst( lst ) return sumArgs( *lst ) # in argument position, the '*' means unpack # (Scheme uses 'apply': (apply sumArgs lst) ) - sequences: x = list("hello") x.sort() http://docs.python.org/tutorial/stdlib.html - importing: giving local names to the other namespace: import random; # can now use `random.randRange(20)` from random import randRange; # can now use `randRange(20)` from random import *; # imports all names not starting w/ `_` The first method is preferred; it's clear to readers where stuff is coming from. Objects in python: - everything public - no fields, really -- each object has its *own* dictionary of bindings, __dict__ - for methods: define a function in the class whose first arg is named (by convention)self . The class can have a special function __init__. - When you access something from an object, (a) first it searches __dict__ for a field (b) if not found it searches the class's __dict__ for a method - Class variables (e.g. Java's static fields) are just attributes to the class object. Note that classes are first-class. (It must always be referenced by the class name, unlike Java.) Example: lect13a.py An example of introspection, to just print out all doc strings: http://www.diveintopython.org/power_of_introspection/index.html
home—info—lectures—exams—hws—archive
©2009, Ian Barland, Radford University Last modified 2009.Dec.04 (Fri) |
Please mail any suggestions (incl. typos, broken links) to ibarland ![]() |
![]() |