One, what is iteration and recursion
Recursion and iteration are all loops.
To put it simply, recursion is the repetition of calling the function itself to implement the loop. An iteration is a loop of code within a function, and the difference between an iteration and a normal loop is that the variable that participates in the operation in the Loop code is also the variable that holds the result, and the current saved result is the initial value of the next loop calculation.
Two, what is an iterator protocol
1. An iterator protocol means that an object must provide a next method that either returns the next item in the iteration, or causes a Stopiteration exception to terminate the iteration (only backward cannot go forward)
2. An iterative object: An object that implements an iterator protocol (how to: Define an __iter__ () method within an object)
3. The Protocol is a convention that iterates over an object, implements an iterator protocol, and Python's internal tools (such as a For loop, Sum,min,max function, etc.) use an iterator protocol to access an object.
PS: (String, list, meta-ancestor, dictionary, collection, file object) These are not iterative objects, but in the for loop, they call their internal __iter__ method, turning them into an iterative object 6
day18-2.py
x= ' Hello ' iter_test=x.__iter__ () print (iter_test) print (iter_test.__next__ ()) print (iter_test.__next__ ()) Print ( iter_test.__next__ ()) print (iter_test.__next__ ()) print (iter_test.__next__ ()) <str_iterator object at 0x000002e0da335978>hello
If you have finished, continue with the iteration error stopiteration
The file is also converted into an iterative object using this method
F=open (' test.txt ', ' r+ ') iter_f=f.__iter__ () print (iter_f.__next__ ()) print (iter_f.__next__ ())
Use while to simulate a for loop thing
L=[1,2,3]DIEDAI_L=L.__ITER__ () while True: try: print (diedai_l.__next__ ()) except stopiteration: Print (' iteration completed, loop terminated ') break123 iteration completed, loop terminated
The above can be operated using the built-in function next day18-4.py
L = [1,2,3,4]iter_l=l.__iter__ () print (Next (iter_l))
1
Python full stack day18 (iterator protocol and for Loop working mechanism)