Main Content

Some gems from an introduction to Python

Archive - Originally posted on "The Horse's Mouth" - 2016-10-29 09:12:59 - Graham Ellis

This week, I ran a private Introduction to Python course - using Python 2.7 at customer request - and here are some of the code snippets I wrote in front of the class - little things I may not have blogged about in the past. Complete examples being emailed to the delegates!

 # Using an exception to see in an object exists (in this case within a dict)
 # --------------------------------------------------------------------------
 
         try:
                 counter[website] += 1
         except KeyError,e:
                 counter[website] = 1
                 print e
 
 # sorting and printing by value
 # -----------------------------
 
 def byvalue(that,this):
         return cmp(counter[this],counter[that])
 
 domains = counter.keys()
 domains.sort(byvalue)
 
 for d in domains:
         print "%-8d %s" % (counter[d],d)
 
 # printing documentation within a test harness
 # --------------------------------------------
 
 if __name__ == "__main__":
         # (main test code here)
         print
         print person.__doc__
 
 # printing with old and new formatters
 # ------------------------------------
 
 print "%8.2f is the value for %-7s today" % (people[person],person)
 print "{0:8.2f} is the value for {1:<7s} today".format(people[person],person)
 
 # How to unwrap a collection into a function
 # ------------------------------------------
 
 sz = (12,16)
 # print getArea(sz[0],sz[1]) ; this is the long-winded way!
 print getArea(*sz)
 
 # decorator ... new and old ways
 # ------------------------------
 
         @staticmethod
         def factory(raw):
                 # code
                 return product
         # decorator at top of method does the following:
         # factory = staticmethod(factory)
 
 # generator ... and list code as comments
 # ---------------------------------------
 
 def places():
         # small = []
         for lyne in fh.xreadlines():
                  (code on line)
                  # small.append(fol[6])
                  print "splash"
                  yield fol[6]
         # return small
 
 # functions that take different parameter patterns
 # ------------------------------------------------
 
 def myrange(*inputs):
         # passed a list
         if isinstance(inputs[0],list):
                 inputs = inputs[0]
         # passed three params
         if len(inputs) == 3:
                 etc
 
 # variety of regular expressions to match a postcode
 # --------------------------------------------------
 
 poco = re.compile(r'[A-Z]{1,2}[0-9]{1,2} {1,}[0-9]{1}[A-Z]{2}')
 poco = re.compile(r'(([A-Z]{1,2})[0-9]{1,2}) {1,}([0-9]{1}[A-Z]{2})')
 poco = re.compile(r'(([A-Z]{1,2})[0-9]{1,2}) {1,}([0-9]{1}[A-Z]{2})$')
 poco = re.compile(r'(([A-Z]{1,2})\d[A-Z0-9]?)\s+([0-9][A-Z]{2})',re.IGNORECASE)
 
 
 # static variable in a function
 # -----------------------------
 
 def more():
         print "dot"
         try:
                 more.keep += 1
         except:
                 more.keep = 1
         print more.keep
 
 # lazy operator, python style with and and or
 # -------------------------------------------
 
 def getNet(amount,vset=None):
         # vatrate is an external (fallback) variable
         vr = (vset == None) and vatrate or vset
 
 
 # using a slice on a string
 # -------------------------
 
 uat = sample.find("u")
 sat = sample.find(" ",uat)
 print sample[uat:sat]