Lecture 13 Iterators Generators
Lecture 13 Iterators & Generators
Announcements
Announcements
0olod山sen ach of hi th notion that Ardu th bodyt Thamy Iterators ody My kArhur-Den Dent,and a an inch ofs ach!【had a weak-beant y fect of the ad From te hcn6oe装是cn4料 fthfromof me. e my pooe bean pves ot in weirnga rabht bone in h se panfolly thranbocn something tha ht check prcuadyy e'd been hopingArhar overwhdofbac d shook it owy of thing of him stood the ed Aid he had supposedy Hey nervouy Hetu beard Hepo nfachestl had the itboent Hepulledd ohedu fe playing illybo Wah e Dntsed the creure.n
Iterators
Definitions Lazy evaluation-Delays evaluation of an expression until its value is needed Iterable-An object capable of returning its members one at a time. Examples include all sequences (lists,strings,tuples)and some non-sequence types(dictionaries). Iterator-An object that provides sequential access to values,one by one. o All iterators are iterables.Not all iterables are iterators. Metaphor:Iterables are books Iterators are bookmarks
Definitions ● Lazy evaluation - Delays evaluation of an expression until its value is needed ● Iterable - An object capable of returning its members one at a time. Examples include all sequences (lists, strings, tuples) and some non-sequence types (dictionaries). ● Iterator - An object that provides sequential access to values, one by one. ○ All iterators are iterables. Not all iterables are iterators. ● Metaphor: Iterables are books & Iterators are bookmarks
two tvhveotvdiloreethree Iterators oneone one How do we create iterators? >>>s [1,2,3]the book >>one,two iter(s),iter(s) iter(iterable):Return an iterator >>next(one)#move bookmark 1 over the elements of an iterable value. 入 This method creates a bookmark from a book starting at the front. >>next(two)#move bookmark 2 1 next(iterator):Returnthenext >>next(one)#move bookmark 1 element in an iterator. 2 Returns the current page and >>next(two)#move bookmark 2 moves the bookmark to the next 2 page. >>three iter(two) The iterator remembers where you >>next(three)#move bookmark 2 3 left off.If the current page is the 3 end of the book,error. >>next(two)#Ran out of pages Stop Iteration
Iterators How do we create iterators? iter(iterable): Return an iterator over the elements of an iterable value. - This method creates a bookmark from a book starting at the front. next(iterator): Return the next element in an iterator. - Returns the current page and moves the bookmark to the next page. - The iterator remembers where you left off. If the current page is the end of the book, error. >>> s = [1, 2, 3] # the book >>> one, two = iter(s), iter(s) one two one two two + three one two + three >>> next(one) # move bookmark 1 1 >>> next(two) # move bookmark 2 1 >>> next(one) # move bookmark 1 2 >>> next(two) # move bookmark 2 2 >>> three = iter(two) >>> >>> next(three) # move bookmark 2 & 3 3 >>> next(two) # Ran out of pages Stop Iteration two
Check Your Understanding:Fibonacci Define a function that returns an iterator that outputs up to the nth value in the Fibonacci sequence.You can assume n will always be 2 or greater Remember,iter(iterable)creates an iterator.Lists are iterables. def fib_iter(n): >>x fib_iter(4) >>next(x) 0 >>next(x) 1 >>next(x) 1 >>next(x) 2 Have you missed me?
Define a function that returns an iterator that outputs up to the nth value in the Fibonacci sequence. You can assume n will always be 2 or greater ● Remember, iter(iterable) creates an iterator. Lists are iterables. def fib_iter(n): """ >>> x = fib_iter(4) >>> next(x) 0 >>> next(x) 1 >>> next(x) 1 >>> next(x) 2 """ Check Your Understanding: Fibonacci Have you missed me?
能 Exceptions Errors
Exceptions / Errors
Exceptions Errors Sometimes,computer programs behave in non-standard ways A function receives a argument value of an improper type Some resources(such as a file)is not available A network connection is lost in the middle of data transmission 10 (Sine chest 1525 1S45 Reloy47o Panel F moti)in clay 好。 First actsal of buq biny found. c2o以Xrm Grace Hopper's Notebook,1947,Moth found in a Mark ll Computer
Exceptions / Errors Sometimes, computer programs behave in non-standard ways - A function receives a argument value of an improper type - Some resources (such as a file) is not available - A network connection is lost in the middle of data transmission Grace Hopper's Notebook, 1947, Moth found in a Mark II Computer
Raise Exceptions Exceptions are raised with a raise statement raise must be an Exception,which is created like so: E.g.,TypeError('Error message') TypeError --A function was passed the wrong number/type of argument NameError --A name wasn't found KeyError--A key wasn't found in a dictionary RuntimeEr ror --Catch-all for troubles during interpretation
Raise Exceptions Exceptions are raised with a raise statement raise must be an Exception, which is created like so: E.g., TypeError('Error message') TypeError -- A function was passed the wrong number/type of argument NameError -- A name wasn’t found KeyError -- A key wasn’t found in a dictionary RuntimeError -- Catch-all for troubles during interpretation
Try Statements Try statements handle exceptions try: except as : Execution rule: 1.The is executed >>>try first ...X=1/0 2.If,during the course of except ZeroDivisionError as e: executing the ,an print('Except a',type(e)) exception is raised that is X=0 not handled otherwise then Except a the is >>>X executed with 0 bound to the exception
Try Statements Try statements handle exceptions try: except as : Execution rule: 1. The is executed first 2. If, during the course of executing the , an exception is raised that is not handled otherwise then the is executed with bound to the exception >>>try ... x = 1/0 ... except ZeroDivisionError as e: ... print('Except a', type(e)) ... x = 0 Except a >>> x 0