python iterators and generators, exceptions

iterator

  • An object that can be called by the next() function and keeps returning the next value (until there is no data and a StopIteration is thrown)
  • l=[1,2,3];
    print(type(l))
    l = iter (l);
    print(type(l))
    for i in l:
        print(i);
    print(next(l));
    print(next(l));
    print(next(l));
  • The iterator internally holds a state, which is used to record the position of the current iteration,
  • In order to facilitate the next iteration to get the correct element
  • Fibonacci sequence demo iterator, generator
  • def fab(max):
        n,a,b=0,0,1
        L=[];
        while n<max:
            #print(b);
            L.append(b);
            a,b=b,a+b;
            n=n+1;
        return L;
    l=fab(10)
    for i in l:
        print(i);
  • iterable class
  • class Fab(object):
        def __init__(self,max):
            self.max=max;
            self.n,self.a,self.b=0,0,1;
        def __iter__(self):
            return self;
        def __next__(self):
            if self.n<self.max:
                r=self.b;
                self.a,self.b=self.b,self.a+self.b;
                self.n+=1;
                return r;
            raise StopIteration ();
    f=Fab(10);
    print(next(f));
    print(next(f));
    print(next(f));
    print(next(f));
    print(next(f));

yield generator

  • def fab(max):
        n,a,b=0,0,1
        while n<max:
            # print(b);
            yield b;
            a,b=b,a+b;
            n=n+1;
    l=fab(10);
    print(next(l));
    print(next(l));
    print(next(l));
    print(next(l));

abnormal

  • a=10;
    b=input('Please enter the dividend:')
    try: # statements that may generate exceptions
        b = int(b);
        c = a / b;
        print(c)
    except Exception: #Catch the exception and handle it
        print('An error occurred!')
        print("The program ended normally..");
  • Multi-channel capture of error information: subclass error first, parent class error after
  • a=10;
    b=input('Please enter the dividend:')
    try:
        b = int(b);
        c = a / b;
        print(c)
    except ZeroDivisionError as zero:#Subclass error
        print('The dividend cannot be 0..Exception information: ',zero)
    except ValueError as v:#Subclass error
        print('Error converting numbers, please input numbers. Exception information: ',v)
    except Exception: #Parent class error
        print('An error occurred!')
    else: # code that will be executed without exception
        print("The program ended normally..")
  • finally: the final content to be executed is written in finally
  • Role: release resources
  • a=10;
    b=input('Please enter the dividend:')
    try:
        b = int(b);
        c = a / b;
        print(c)
    except ZeroDivisionError as zero:#Subclass error
        print('The dividend cannot be 0..Exception information: ',zero)
    except ValueError as v:#Subclass error
        print('Error converting numbers, please input numbers. Exception information: ',v)
    except Exception: #Parent class error
        print('An error occurred!')
    else: # code that will be executed without exception
        print("The program ended normally..");
    finally:
        try:
            of a, b, c
        except Exception as e:
            print (s)
        print("finally: release resources quickly");
    print('Program other code');

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325446172&siteId=291194637