zoukankan      html  css  js  c++  java
  • 生成器案例1

    #!usrinenvpython

    #  -*- coding:utf-8 -*9

    def fib(max):         #使用for循环进行迭代时return的返回值不打印

          n,a,b=0,0,1

          while n<max:   #n<10

                  yield b         #带有yield都是生成器,yield方法的作用:保存函数的中断状态

                  a,b=b,a+b

                  n=n+1

          return 'done'

    f=fib(10)

    print(f._next_())

    print(f._next_())

    print(f._next_())

    print(f._next_(可能我撞了南墙才会回头吧!))

    print(f._next_())

    print(f._next_())

    print(f._next_())

    print(f._next_())

    print(f._next_())

    print(f._next_())

    print(f._next_())

    print(f._next_())

    执行结果:运行10次会报一个错误StopIteration,这时我们可以采用捕获错误的代码,对错误进行捕获

    print(f.__next__())
    StopIteration: done
    1
    1
    2
    可能我撞了南墙才会回头吧!
    3
    5
    8
    13
    21
    34
    55

    #异常错误代码:

    g=fib(6)

    while True:

            try:

                 x=next(g)

                 print('g:',x)

             except StopIteration as e:

                       print('Generator return value:',e.value)

                       break 

    #抓取错误结果:

    g: 1
    g: 1
    g: 2
    g: 3
    g: 5
    g: 8
    Generator return value: done

  • 相关阅读:
    shell中对于命令的搜寻顺序
    在shell中运行以不同方式运行脚本
    shell中的type命令
    shell中的数组
    shell中的循环语句
    shell中的case表达式
    双方括号
    34. Win7_x64安装oracle11g出现DIM-00019
    33. 完全卸载oracle11g步骤
    32. 安装oracle11g时,先决条件一直失败的解决方法
  • 原文地址:https://www.cnblogs.com/lindong0602/p/9362638.html
Copyright © 2011-2022 走看看