Getting Started in Python Gene Cooperman To learn these concepts, it is best to run Python in another window, and type in these examples, or use cut-and-paste. This is based on Python 2.7, but most of this applies equally to Python 3.x. 0. Python uses ':' and indentation instead of the more traditional '{', '}': When you type this, a top level stmt, such as "x = 1" must begin in column 0. I type the top-level stmt already indented for readability only. x = 1 while x <= 10: print (x) x = x + 1 1. Basic functions: len, split, join, range, + (concatenate strings or lists) (Examples of all of these functions exist later.) Other functions: int, str, float, list, set, tuple (Used to cast object to int, str, float, list, set, tuple) (A set is like a list, but it has no duplicates.) (A tuple is like a list, but it cannot be changed.) enumerate (An example of 'enumerate' exists later.) zip (An example of 'zip' exists later.) Other functions: Basic methods for lists: x = [3,4,5] x.append(6) x.extend([7,8,9]) Basic methods for strings: y = "This is a\npiece of text." print ("piece of" in y) # This will return: True words = y.replace('.', '').split() sentence = ' '.join(words) A common mistake: print ("The answer is: " + 42) (You can't concatenate a string and an int.) Fixing the common mistake (convert the int to a string): print ("The answer is: " + str(42)) 2. Online help is always available: help(range) help(len) help([3,4,5].append) help(' '.join) help(str) help(list) help(enumerate) 3. Python allows you to place on a single line logic that would normally take many lines. Read from left-to-right or from middle-to-outside. x = "The quick brown fox jumps over the lazy dog." print ( "The number of different letters in the sentence is: " + str(len(set(x.lower().replace('.','').replace(' ','')))) ) 4. Slices: days = ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun'] weekdays = days[:5] weekends = days[-2:] # last two elements middleOfWeek = days[1:4] calendarDays = [days[-1]] + days[:6] # 'Sun' comes first now 5. For loops: y = [] for x in range(10): y.append(x) 6. Other control structures: while break, continue (inside for or while loop) def foo(x,y): return x+y 7. List comprehension: [ x**2 for x in range(10) if x % 2 == 1 ] 8. List comprehension with nested 'for' stmts: [ str(i)+' x '+str(j)+' = '+str(i*j) \ for i in range(11,13) for j in range(11,13) if i <= j ] x = "The quick brown fox jumps over the lazy dog." print ( "The repeated letters are: " + str(''.join(sorted(set( [letter for letter in x if x.count(letter)>1] )))) ) 9. A 'for' loop with multiple indexes: # Copy k characters from index i to index j in the list x: x = list(range(0,9)) (i,j,k) = (3,6,2) for a, b in zip( range(i,i+k), range(j,j+k) ): x[b] = x[a] print( x ) # 'zip' is a zipper function. Try printing it as a list: print( list(zip( range(i,i+k), range(j,j+k))) ) 10a. Easy parsing: output = "x:3.12; y:4.57\n x:5.6; y:7.8\n x:2.4; y:3.5\n" fields = output.replace(';',' ').replace(':',': ').split() xValues = [ float(fields[i]) \ for i in range(1,len(fields)) if fields[i-1] == 'x:' ] yValues = [ float(fields[i]) \ for i in range(1,len(fields)) if fields[i-1] == 'y:' ] xyPairs = zip(xValues, yValues) yAverage = sum(yValues) / len(yValues) 10b. Easy parsing: command = "./a.out --min 42 --max 57 --input file.in" max = [ command[idx+1] for idx, word in enumerate(output.split()) if word in ["--max-value", "--max", "-m"] ][0] 11. Reading and writing files: tmpFile = open("tmp.tmp", 'w') for x in range(10): tmpFile.write( str(x) + ": " + str(x*x) + '\n' ) tmpFile.close() readTmpFile = open("tmp.tmp", 'r') lines = readTmpFile.readlines() print ( str(len(lines)) + " lines were read." ) readTmpFile.close() 12. EXERCISES: Next, try some Python exercises. One good source is: http://codingbat.com/python Most of those exercises can be done in one or two lines using list comprehension. 13. FURTHER READING: help(list) help([]) help([].append) help(str) google: python str http://docs.python.org/2/library/stdtypes.html#mutable-sequence-types Other data structures: help(set), help(dict) I/O: help(file) 14. ADVANCED: If you use lists of lists in Python and other advanced data structures, start to explore the difference between shallow copy and deep copy: id(mylist) newlist = mylist # identical copy: id(newlist) == id(mylist) newlist = mylist[:] # shallow copy import copy; copy.deepcopy(mylist) # deep copy 15. ADVANCED: Python also has dictionaries and classes. In many cases, these are clearer to read than the above lists of lists. A. Dictionaries: point = {'x_val': 3.1, 'y_val' : 17.0} point['x_value'] = 5.6 ; z = point['y_val'] B. Simple Classes: Python provides a fully developed class system. But the book "Python Cookbook" describes some nice lightweight, easy classes: http://books.google.com/books?id=Q0s6Vgb98CQC&dq=Python%20Cookbook%20%22Collecting%20a%20Bunch%20of%20Named%20Items%22&hl=en&pg=PT214#v=onepage # For _simple_ classes, just copy this example magic class definition. class Point(object): def __init__(self, **kwds): self.__dict__.update(kwds) def __repr__(self): return "%r" % (self.__class__.__name__, self.__dict__) mypoint = Point(x_val=3.1, y_val=17.0) mypoint.x_val = 5.6 ; z = mypoint.y_val ; mypoint C. Simple Classes with Methods: # We add the dist_from_origin method to the class Point. class Point(object): def __init__(self, **kwds): self.__dict__.update(kwds) def __repr__(self): return "%r" % (self.__class__.__name__, self.__dict__) def dist_from_origin(self): import math return math.sqrt(self.x_val ** 2 + self.y_val ** 2) mypoint = Point(x_val=3.1, y_val=17.0) mypoint.dist_from_origin() 16. ADVANCED: A function object is just another type, like anything else. Notice the difference between: type(range) --> type(range(5)) --> type("range") --> So, help(range) and help(range(5) produce different answers. For help("range"), Python tries to be clever and "do what you mean". Think about why these work: def foo(x): return x+1 def bar(): return foo bar()(7) --> 8 def foo(x): return x+1 y = 15 [foo,y][0](7) --> 8 z = foo z(7) --> 8 17. ADVANCED: Use Python's 'assert' statement widely in your code. This can be thought of as an executable comment. Note that 'python -O' will ignore assert statements.