#! /usr/local/bin/python3 # cheat sheet for Python version 3 (and some version 2) import sys # inspired by Python Programming from WIkibooks print("Hello, world") print("""\ Usage: ./cs.py and no arguments """) lucky = 7 print(lucky) print("Hello"+" "+"there!") print("The name of this program is "+sys.argv[0]) print ("Please give me a number: ") #number = raw_input() # this function in Python 2 #number = input() # was renamed in Python 3 number = 6 # let's focus on Python 3 # functions int and str convert strings to integers and back # len returns string length # apparently Python is stricter about types than Perl... plusTen = int(number) + 10 print ("If we add 10 to your number, we get " + str(plusTen)) print ("That input string was of length "+str(len(str(number)))) # variables are case-sensitive # blanks and tabs are different # Python is O-O, so print('bob'.upper()+" should be BOB") print("What objects are in the default namespace?") print(dir()) print("What is the type of plusTen?") print(type(plusTen)) print("Let's import the math module") import math print("and see what objects we now have...") print(dir(math)) print("the square root of 2 is ") print(math.sqrt(2)) # print can take floats, apparently # strings can be subscripted print("The first character of 'Robert' is "+'Robert'[0]) # negative subsripts count from the end of the string print("The last character of 'Robert' is "+'Robert'[-1]) # lists are delimited by square brackets # and can be subscripted # len works as you'd expect foo = ["able","baker","charlie"] print("First element of foo is "+foo[0]) print("Last element of foo is "+foo[-1]) # but list elements need not be of the same type # for homogeneous lists, use arrays foo.append(17) print("Now, the last element of foo is "+str(foo[-1])) # insert places a new element at a designated subscript foo.insert(3,"delta") del foo[0] # note that del is a statment, not a function... print("Now, foo is ") print(foo) # list assignemnt seems to be a pointer assignment, # so that changes to foo2 affect foo print(foo) foo2 = foo foo3 = foo[:] # this form seems to be an actual copy foo2[0] = "cat" print(foo) print(foo3) # assignment statements can have multiple l-vals print("Welcome to the Fibonacci Sequence") a, b = 0, 1 while b < 10: print(b) a, b = b, a+b # iterators work over iterable objects, such as the range operator # tuples are declared with commas, and are immutable # but otherwise are like lists, I suppose origin = 0,0 print("where is the origin?") print(origin) # dictionaries are manage keys and associated values # using curly braces # and sorteddict are sorted dictionaries ngrams = {"aa":0, "bbb":3} print(ngrams) # and we have sets, and (immutable) frozensets # and a variety of data types, some mutable and others immutable # and here's a simple function # special value None is used to specify defaults def fourth_root (x, type = None): result = math.sqrt(math.sqrt(x)) return result print(fourth_root(4)) # python has a float type of course print(-4 + 0j) # python also has a complex type print(2 + (-4 + 0j)) # python also has a complex type print("Here is an octal constant") print(0o77) print("Here is a hex constant") print(0xff) print("""sometimes a string can span a line break""") # if is a basic control structure item = 12 if item == 1: print("item is one") else: print("print in else clause") # equality of value is tested with == # equality of location in memory is tested with is # tesing is None is a best practice # string replication is supported print("Hello "*3) # the in operator works for strings if "ly" in "Hello": print("found it") else: print("no joy") # the in operator works for lists too if "cat" in ("cat","dog"): print("found it") else: print("no joy") # the operator a:b takes a string (or list) slice # if a or be is omitted, it uses first or last print("Snagelpuss[1:4] is "+"Snagelpuss"[1:4]) # prints nag print("Snagelpuss[6:] is "+"Snagelpuss"[8:]) # prints ss # lots of builtin string functions print("Hello, world".count('l')) # list comprehensions as in Haskell, sortof listOfWords = ["this","is","a","list","of","words"] items = [ word[0] for word in listOfWords ] print(items) zeros = [0]*5 # and replication print(zeros) # list concatenation can be done in at least two ways print(["cat","dog"]+["eagle","fox"]) a = ["cat","dog"] b = ["eagle","fox"] b.extend(a) # for some reason, preferred inside lambdas b.sort() print(b) print("one at a time") item = 0 for element in b: print(element) item += 1 # options for making shallow vs. deep copy # for loop for i in range(0,10,2): # doesn't print 10, for some reason print(i) a = range(0,10,2) print("min, max, and sum are builtin") print(min(a),max(a),sum(a)) del a # don't need this list anymore # tuples can be l-vals, as in Perl and R #u,s,vt = svd(tdm) def quadeq(a,b,c): discrim = (b**2)-(4*a*c) if discrim == 0: oneRoot = -b / (2*a) return(oneRoot, oneRoot) elif discrim > 0: return(-b+math.sqrt(discrim),-b+math.sqrt(discrim)) else: # else if available for other control structures! return(None,None) (root1,root2) = quadeq(1,2,1) print((root1,root2)) # dictionaries are useful... dict1 = {} # Create an empty dictionary dict2 = dict() # Create an empty dictionary 2 dict2 = {"r": 34, "i": 56} # Initialize to non-empty value equalbyvalue = dict1 == dict2 isempty2 = len(dict2) == 0 # Emptiness test for key in dict2: # Iterate via keys print (key, dict2[key]) # Print key and the associated value for value in dict2.values(): # Iterate via values print (value) dict3 = dict2.copy() # A shallow copy dict3.update({"i": 60, "j": 30}) # Add or overwrite print (dict1, dict2, dict3, equalbyvalue) del dict3["i"] print(dict3) # opertions on sets extend lists, with usual operations like union # comprehensive repertoire of functions... x = 5 while x > 0: print(x) x = x - 1 # break and continue as in C # varying number of arguments is supported def concat(*args, sep="/"): return sep.join(args) print(concat("earth", "mars", "venus")) # call by reference seems to be the norm print("Example of lambda expression") print( (lambda a, b: a + b) (4, 3) ) # example of closure, and returning a function def attribution(name): return lambda x: x + ' -- ' + name pp = attribution("Charles") print(pp('Curry, anyone?')) # formatted I/O is similar but not quite the same as printf print('The value of PI is approximately %5.3f.' % math.pi) # read this file in as a string f = open(sys.argv[0],'r') aBigString = f.read() print ("This file "+sys.argv[0]+" has a length of "+str(len(aBigString))) # and the file handle is iterable #for line in f: # print(line, end='') # pickling refers to printing a Python object by reasonable use of str # and of course Python lets you define classes class R2Point: "An example class for points on the Cartesian plane" def __init__(self): self.__x = 0 self.__y = 0 @property def x(self): return self.__x @x.setter # can be used on left side of an assignment def x(self, xVal): self.__x = xVal @property def y(self): return self.__y @y.setter def y(self, yVal): self.__y = yVal # properties are attributes with get and set methods #x = property(getx, setx) #y = property(gety, sety) # an example of a static method def print(self): print(self.x,self.y) pass # pass is a do-nothing statement, a placeholder # create an instance of RPoint aPoint = R2Point() aPoint.x = 1 aPoint.y = 2 aPoint.print() print("Should have printed:") print(aPoint.x) print(aPoint.y) print("The members of aPoint are:") print(vars(aPoint)) print("which should be the same as") print(aPoint.__dict__) # but now we can add members dynamically aPoint.__dict__['z'] = 4 memberDkeys = aPoint.__dict__.keys() print(memberDkeys) print("should look like") print(aPoint.x) print(aPoint.y) print(aPoint.z) class Vertex(R2Point): "inherits all the methods and properties of R2Point" # __del__: # deletes the onstance # __str__: # returns string form of the instance # and function names to add, get, and delete attributes are available # __add__: # method allows use of infix + # __iadd__: # method allows use of infix += # __neg__: # method alows use of prefix unary minus # other overrides are available pass # metaclasses look a little like ML functors # not sure I understand decorators # can import some or all functions from a module, e.g. #from math import sqrt # if a file myModule has class definitions in it, import it like so: # import myModule # try except # to install requests, I got the zipball from github, unzipped it, # and ran python3 setup.py install from the new directory # other packages e.g. numpy are even easier to install import requests url = 'http://www.google.com' # takes too long #try: # r = requests.get(url) # print(r.status_code) # print(r.text[0:20]) #except: # print("Problem accessing "+url) #finally: # get regular expressions and sockets going import re import socket import numpy mydata = [numpy.random.normal(0,1) for i in range(10000) ] h, n = numpy.histogram( mydata , 100, (-5,5) ) print(h) # extensive capabilities for XML, threads, networking, DBMS, and more