DePaul University | DePaul University, Chicago



Python - Mini-API / Cheat SheetNote:I realize that the cheat-sheet may include some functions / techniques that may be unfamiliar. This is especially true for the midterm exam where there may be things on this cheat-sheet that we have not yet covered in the course. I will not, of course, ask you anything that we have not discussed in lecture. For example, if we have not yet covered classes or tuples, etc by the midterm exam, then I will certainly not be asking about them on that exam. You are expected to know how to use all of the basic string functions. Stringss.capitalize()Returns the capitalized version of s. # 'hello' => 'Hello's.lower()Returns the lower case version of s. # 'HELLO' => 'hello's.swapcase()Returns the swapped-case version of s. # 'Hello' => "hELLO"s.title()Returns the title case version of s. # 'hello world' => 'Hello World's.upper()Returns the upper case version of s. # 'hello' => 'HELLO's.replace(s2, s3)Replace s2 with s3 in s. Returns the string.s2 in sReturn true if s contains s2s + s2Concatenates s and s2len(s)Returns length of smin(s)Returns smallest character of smax(s)Returns largest character of ss * integerReturns 'integer' copies of 's' concatenated # 'hello' => 'hellohellohello's2 not in sReturn true if s does not contain s2s.find(s2)Find and return lowest index of s2 in s. Returns -1 if not present.s[index]Returns character at index of ss.count(s2)Returns count of s2 in ss.index(s2)Returns lowest index of s2 in s (but raises ValueError exception if not found)s.islower()Return true if s is lowercases.isupper()Return true if s is uppercases.split(sep, maxsplit)Return list of s split by sep with leftmost maxsplits performeds[i:j]Slice of s from i to j Dictionaries emptyDict = {} #creates a new empty dictionarythisdict = {'a':1, 'b':23, 'c': 'eggs'} #new dictionary with some datathisdict['a'] #returns 1 thisdict['a'] = 34 #assigns the value 34 to the key 'a'thisdict['ZZZZZ']=25 #creates a NEW key called 'ZZZZZ' (unless that key already exists)#and assigns a value of 25 to that keythisdict.keys() #returns ['a', ,'b', 'c'] thisdict.values() #returns [1, 23, 'eggs'] thisdict.items() #returns [('a', 1), ('b',23), ('c', 'eggs')] Deleting: del thisdict['b'] Retrieving: thisdict.has_key('e') #returns False 'c' in thisdict #returns True 'paradimethylaminobenzaldehyde' in thisdict #returns FalseSome important methods of class list:sort() #returns a sorted copy of the listappend(x) #appends 'x' to the listremove(item)#removes item from the list if presentOther useful methods / operators for use with lists:item in someList #returns a boolean (e.g. True if item is present)len(list) #returns the number of items in listOutline of a function:def identifier( <parameters> ):code here… Optional return statementOutline of if/else block:if conditionalA and conditionalB:code hereelif conditionalC or conditionalD:code hereelse:something elseOutline of exception handling block:try:Do somethingexcept <optional exception types>:code to handle the exception goes hereTuplesemptyTuple = ()nonemptyTuple = (3,'yellow', 48)nonemptyTuple[2] #returns 48SetsmySet = {4,7,9,2}mySet.add(34) #adds 34 to the setFormat String:favColor = 'blue'name = 'bob'sentence = "{}'s favorite color is {}".format(name, favColor)for loops & range()Say you have a list called "collection", the following will output all items in that list:for item in collection:print(item)for i in range(2,5): print(i) #will print 2,3,4 (on separate lines)I expect that you can convert the above loops into a nested loop as needed.while loops:while <conditional>:Code CodeCodebreak #exits (i.e. terminates) a loop Methods for working with input file objects:fin = open(some_file,'r')fin.read() #reads some_file as one stringfin.readline() #reads in the next line ahead of the cursor, returns a stringfin.readlines() #reads in all lines beginning at the cursor; returns a list #Writing to a file:fout = open('some_file.txt','w')fout.write('I am ' + str(20) + ' year old.') #Note that write() requires a string as its argument#OR:s = 'I am {} years old'.format(20)fout.write(s)fout.close() A few useful functions from the 'random' module:random.randint(1,n) #returns a random integer between 1 and nrandom.shuffle(some_list) #returns the list in a new orderrandom.choice(some_list) #returns a random value out of some_listA few useful functions from the 'math' module:math.ceil(x) #returns the ceiling of x e.g. math.ceil(33.2) returns 34math.floor(x) #returns the ceiling of x e.g. math.floor(33.9) returns 33math.pow(x,y) #returns the x to the power of y. of x e.g. math.pow(3,2) returns 9math.sqrt(x) #returns the square root of x e.g. math.sqrt(25) returns 5.0Date and Time: Retrieving the date and time (e.g. used for timestamps)timestamp = datetime.datetime.now()#print(timestamp) #would output something like:#2019-05-03 08:09:43.511541PRECEDENCE TABLE OperatorDescription(expressions...), [expressions...], {key:datum...}, `expressions...`Binding or tuple display, list display, dictionary display, string conversionx[index], x[index:index], x(arguments...), x.attributeSubscription, slicing, call, attribute reference**Exponentiation [8]+x, -x, ~xPositive, negative, bitwise NOT*, /, //, %Multiplication, division, remainder+, -Addition and subtraction<<, >>Shifts&Bitwise AND^Bitwise XOR |Bitwise OR in, not in, is, is not, <, <=, >, >=, <>, !=, ==Comparisons, including membership tests and identity tests,not xBoolean NOTandBoolean ANDorBoolean ORlambdaLambda expressionCommon Sequence OperationsThe following methods work on most sequence types – both mutable and immutable: (e.g. lists, tuples, etc). OperationResultx?in?sTrue?if an item of?s?is equal to?x, else?Falsex?not?in?sFalse?if an item of?s?is equal to?x, else?Trues?+?tthe concatenation of?s?and?ts[i]ith item of?s, origin 0s[i:j]slice of?s?from?i?to?jlen(s)length of?smin(s)smallest item of?smax(s)largest item of?ss.index(x])index of the first occurrence of?x?in?s?s.count(x)total number of occurrences of?x?in?sThe functions below only work on mutable sequence types (e.g. lists)OperationResults[i]?=?xitem?i?of?s?is replaced by?xdel?s[i:j]same as?s[i:j]?=?[]del?s[i:j:k]removes the elements of?s[i:j:k]?from the lists.append(x)appends?x?to the end of the sequence (same ass[len(s):len(s)]?=?[x])s.clear()removes all items from?s?(same as?del?s[:])s.insert(i,?x)inserts?x?into?s?at the index given by?i?s.pop([i])retrieves the item at?i?and also removes it from?ss.remove(x)remove the first item from?s?where?s[i]?==?xCreation of a Class:class Point(object): 'stores two coordinates, x and y' def __init__(self,xCoord=0,yCoord=0): self.x = xCoord self.y = yCoord def __str__(self): s = 'x: {}\ny: {}\n'.format(self.x,self.y) return s def __add__(self,other): 'returns a new Point with the coordinates added' newX = self.x + other.x newY = self.y + other.y return Point(newX,newY) def setX(self, newX): self.x = newX def setY(self, newY): self.y = newY def move(self,newX,newY): self.x = newX self.y = newY def __eq__(self,other): return self.x == other.x and self.y==other.yOutline of HTMLParser Class:Note: The following simply demonstrates the 3 methods that we have talked about in this class that you would need to override in a subclass when working with web pages.class HTMLParser(object): def handle_starttag(self, tag, attrs): pass def handle_endtag(self,tag): pass def handle_data(self, data): passHere is code you might use to work with your derived HTMLParser classes:from html.parser import HTMLParserfrom urllib.request import urlopenurl = ''content = urlopen(url).read().decode('Latin_1')parser = HTMLParser() parser.feed(content) ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download