Iterator, essence of for loop, comparison between iterative value and index value, advantages and disadvantages of iterator, exception handling

Posted by jess3333 on Tue, 11 Jan 2022 13:14:32 +0100

iterator

What is an iterator

Iterators are tools that iterate values

What is iteration

Iteration means updating, and each update iteration must depend on the results of the previous one

l = [111, 222, 333]  # Traversal list, index, iterative value
nums = "hello" 

def get(l):  # Functions are value taking tools
    i = 0
    while i < len(l):
        print(l[i])  # The results of each time are based on the previous time
        i += 1
get(l)   
  • Why use iterators

    • 1. Iterators provide a way to iterate values independent of the index
    • 2. Save memory

 

 

 

Iteratable object

  • Built in__ iter__ Methods are called iteratable objects

    • Calling an iteratable object__ iter__ Method, which returns an iterator object

# Built in types are iteratable objects
s = "abc"  # character string
l = [11, 22, 33]  # list
d = {'k1': 111}  # Dictionaries
t = (11, 22, 33)  # tuple
se = {11, 22, 33}  # aggregate
f = open('a.txt',mode='wt')  # The file object itself is an iterator object

"""
contain__iter__Yes
    String list dictionary tuple collection file object
 These are usually iteratable objects
 Built in means that you can view it directly by clicking
"""
print(d)  # {'k1': 111}
print(d.__iter__())  # <dict_keyiterator object at 0x7fbb4f787db0>
print(iter(d))  # <dict_keyiterator object at 0x7fbb4f787db0>
print(d.__len__())  # 1
print(len(d))  # 1
"""
Iteratable object call__iter__Method becomes an iterator object(Old sow)

__iter__There is also a simple way to write method when calling iter()
Generally, all double drop methods will have a corresponding simplified version method name()
"""

Iterator objects

  • Built in existing__ iter__ Methods, and__ next__ Methods are called iterator objects

    • Calling the iterator object__ iter__ The method gets the iterator object itself, just like it was not called

    • Calling the iterator object__ next__ Method returns the next value, independent of the index

    • Can be called all the time__ next__ Until it is clean, an exception StopIteration is thrown

 

# Iterator direct value method
l = [111, 222, 333]

l1 = l.__iter__()  # Turn the iteratable object into an iterator object, the source list does not move, and a new one is generated

print(l1)  # <list_iterator object at 0x7fe1708378e0>

print(l1.__next__())  # 111 Iterator object execution__next__Method is actually iterative value taking(for loop)
print(l1.__next__())  # 222
print(l1.__next__())  # 333
print(l1.__next__())  # The exception StopIteration thrown was not found

'''
__next__Method also has a simple way to write when calling iter()
'''
res = iter(l)
print(next(res))  # 111
print(next(res))  # 222
print(next(res))  # 333


# Loop prints out each element in the list
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55]
l_iter = iter(l)  # Turn the iteratable object into an iterator object first

while True:  # Loop execution__ next__ Value
    try:  # Exception handling: check whether the code will report an error
        res = next(l_iter)
        print(res)
    except StopIteration:  # Catch exceptions and end the loop
        break

# Replace the above method with two lines of code for the loop  
for res in l:  
    print(res)
    
"""
for Internal principle of circulation
    1.Will keyword in The following data is called first__iter__Method to an iterator object
    2.Loop execution__next__method
    3.After taking it__next__Will report an error, but for The loop automatically catches the error and handles it
"""

Advantages and disadvantages of iterators

advantage:

      1,It provides a unified iterative method for sequential and non sequential types.
      
        2,Lazy Computing: an iterator object represents a data flow that can be called only when needed__next__To calculate a value, in terms of the iterator itself,
        There is only one value in memory at the same time, so it can store infinite data streams. For other container types, such as lists, all elements need to be stored in
        In memory,Due to the limitation of memory size, the number of values that can be stored is limited.

shortcoming

      1,The length of the iterator cannot be obtained unless it is exhausted
      
      2,You can only take down one value. You can't go back to the beginning. It's more like'disposable',After the iterator is generated, the only goal is to repeat the execution next Method until the value is exhausted, otherwise
        Will stay in a position and wait for the next call next;If you want to iterate over the same object again, you can only call it again__iter__Method to create a new iterator
        Object, if two or more loops use the same iterator, there must be only one loop that can get the value.

 

exception handling

 

  • What is an exception

    • An exception is a signal of a program error. Once the program has an error, it will throw an exception. If there is no solution after the exception, the whole program will end

 

Exceptions are three important components

  • 1. Traceback

    • Turn to the first blue font from bottom to top and click with the left mouse button to jump to the line where the wrong code is located
  • 2. XXXError

    • Wrong type
  • 3. Error type content after colon

    • Detailed cause of the error (very important. After careful reading, you may find a solution)

 

There are two types of errors

  • 1. Syntax error

    • Not allowed. This error must be corrected before the program runs
  • 2. Logical error

    • For controllable logic errors, they should be solved directly at the code level

    • For uncontrollable logic errors, try except... (a remedial measure after an abnormality occurs)

 

Controllable logic error

    • If the condition of the error is predictable, we need to use if to deal with it: prevent it before the error occurs
age = input(">>>: ").strip()
if age.isdigit():
    age = int(age)

    if age > 19:
        print('too big')
    elif age < 19:
        print('too small')
    else:
        print('you got it')
else:
    print('You must enter a number')
    
'''The process of correcting logical errors is actually the process of clarifying ideas from beginning to end'''

Uncontrollable logic error

  • If the condition under which the error occurs is unpredictable, try Except: process after the error occurs
"""
How to use try...except
 Basic syntax structure:
    try:
        Code with possible exceptions
    except Type of exception as e:
           Corresponding processing mechanism after exception(e Is the details of the exception)
    except Type of exception as e:
            Corresponding processing mechanism after exception(e Is the details of the exception)
        except (Exception type 1,Exception type 2) as e:
            Corresponding processing mechanism after exception(e Is the details of the exception)
        except Exception:  # Universal exception, when all the above exception handling are not right, this exception handling will be run finally
            Corresponding processing mechanism after exception(e Is the details of the exception)
        else:
            Code to execute when no exception occurs
        finally:
            Whether abnormal or not,Will execute this code, which is usually used to recycle resources
"""

# Example 1
try:
    print(111)
    print(222)
    l=[11, 22, 33]
    l[100]  # abnormal
    print(3333)
except IndexError as e: # If the exception matching is successfully captured and printed e, the program will not crash
    print(e) 
    
'''
111
222
list index out of range List index out of range
'''

# Example 2
try:
    print(111)
    l=[11, 22, 33]
    l[100]
except KeyError as e:  # If the exception type does not match successfully, the program will crash
    print(e)
'''
111
222
Traceback (most recent call last):
  File "/Users/gengfeng/Python20/Day14/exception handling.py", line 16, in <module>
    l[100]
IndexError: list index out of range
'''

# Example 3
try:
    print(111)
    print(222)
    l=[11,22,33]
    l[0]
    dic = {'k1':111}
    print(3333)
except Exception as e:  # Universal exception, any exception can be right
    print(e)
else:  # Execute if there is no exception in the code block in try
    print('else Code of')
finally:  # The module is executed whether it is abnormal or not, usually for cleaning
    print('finally Code of')
    
'''
111
222
3333
else Code of
finally Code of
'''

"""
Exception capture sentence patterns and universal exceptions
    1.Code that may have errors needs to be monitored
    2.The less code to be monitored, the better
    3.The lower the frequency of exception capture, the better
"""

Common exceptions

l=[]
l[100]

'''
IndexError: list index out of range
 Index error: list index is out of range 
'''

dic={}
dic["k1"]
'''
KeyError: 'k1'  
key Error:'k1'
'''
 
int("asdb")
'''
ValueError: invalid literal for int() with base 10: 'asdb'
Wrong value: invalid int()The base number of is 10:'asdb'  
'''

1/0  
'''
ZeroDivisionError: division by zero 
# Zero division error: divide by zero    
''' 

def func(x):
    pass

func() 
'''
TypeError: func() missing 1 required positional argument: 'x'
Wrong type: func()1 required positional parameter is missing:'x'
'''

x
'''
NameError: name 'x' is not defined   
Name error: name'x'Undefined
'''
    
print('asdfadf'
'''     
SyntaxError: unexpected EOF while parsing  
Syntax error: unexpected error parsing EOF     
'''          

Assertions (understand)

  • Judge whether the condition meets the standard, and throw an exception if it does not meet the standard
  • It can be used when testing the program. It should be deleted after testing

 

l = [111, 222]
# Judge that if the length of l is not equal to 3, it will actively throw an exception
if len(l) != 3:      
    raise Exception('Three values must be reached')  # Exception: three values must be reached 
'''  
assert: Judge that the conditions meet the standard, execute the program normally, and throw an exception if they do not meet the standard 
raise: Active exception throwing can be used when setting rules for others
'''  
# If the length of assertion l is equal to 3, an exception will be thrown if the assertion fails      
assert len(l) == 3  # The effect is the same as above (recommended)
print('Follow up code...')

# Actively throw index error
raise IndexError("Index error")  # IndexError: index error

 

 

Types of anomalies

  • In python, different exceptions can be identified with different types. An exception identifies an error

 

# Common anomalies

IOError input/Abnormal output; Basically, you can't open the file

ImportError Unable to import module or package; It's basically a path problem or a wrong name

IndentationError Syntax error (subclass of); The code is not aligned correctly

IndexError The subscript index exceeds the sequence boundary, such as when x There are only three elements, but you try to access them x[5]

KeyError An attempt was made to access a key that does not exist in the dictionary

KeyboardInterrupt Ctrl+C Pressed

NameError Use a variable that has not been assigned to an object

SyntaxError Python Illegal code, code cannot be compiled(Personally, I think it's a grammatical mistake (wrong writing)
                              
TypeError The incoming object type does not match the required
                              
UnboundLocalError An attempt to access a local variable that has not been set is basically due to another global variable with the same name,
                  Cause you think you're visiting it
                              
ValueError Pass in a value that the caller does not expect, even if the value type is correct
                              
AttributeError Trying to access a tree without an object, such as foo.x,however foo No attributes x