zoukankan      html  css  js  c++  java
  • Python 进阶 之 else块 巧(慎)用

    Python 的 else 模块和其他语言的else模块相比有那么一丢丢的特殊用法,有些用法虽然不推荐用,但是别人如果用了,最起码能看懂是不是?

    1:快捷返回值: 

    格式:
        value1 if expression else value1
      #
    expression 为真,返回value1,expression为假,返回value2

    >>> print 1 if 1 else 0
    1
    >>> print 1 if 0 else 0
    0
    >>>

    2: if - elif - else 表达式:

     格式:

    if expression1:
      value1
    elif expression2:
       value2 
    else:
       value3
    #expression1 为真,返回value1,expression2为真,返回value2,否则返回value3
    >>> if 0 == 2: 
    ...
    print 2
    ...
    elif 0 == 1:
    ...
    print 1
    ...
    else:
    ...
    print 0
    ...
    0
    >>>

    3:for - else 表达式:

    for expression:
        if not loop-expression:
         value1
    break else: value2
    #
    expression 为假,跳出循环,执行value2,loop-expression为假,跳出循环,执行value1
    >>> for i in xrange(3):
    ...     if i > 1:
    ...         print "loop-expression"
    ...         break
    ... else:
    ...     print "else block"
    ... 
    loop-expression
    >>> for i in xrange(3):
    ...     if i > 4:
    ...         print "loop-expression"
    ...         break
    ...else:
    ...    print "else block"
    ... 
    else block

    3:while - else 表达式:

       与for - else 类似,不再赘述。

    4:try - except - else - finally 模块

    try:
    expression
    except:
    value1
    else:
    value2
    finally:
    value3
    #执行try内expression
    1:执行异常,输出value1,value3
    2:执行正常,输出value2,value3

    >>> try: ... 1 == 1 ... except: ... print "error" ... else: ... print "else block" ... finally: ... print "finally block" ... else block finally block
    >>> try:
    ...     x == 1
    ... except:
    ...     import traceback
    ...     print "------- except start -------"
    ...     traceback.print_exc()
    ...     print "------- except stop  -------"
    ... else:
    ...     print "else block"
    ... finally:
    ...     print "finally block"
    ... 
    ------- except start -------
    Traceback (most recent call last):
      File "<stdin>", line 2, in <module>
    NameError: name 'x' is not defined
    ------- except stop  -------
    finally block
  • 相关阅读:
    怎样从外网访问内网数据库?
    怎样从外网访问内网Linux系统?
    怎样从外网访问内网Nginx?
    使用Holer外网SSH访问内网(局域网)Linux系统
    使用Holer远程桌面登录家里电脑和公司内网电脑
    使用Holer将本地端口映射到公网
    使用内网映射工具Holer将本地的Web应用映射到公网上访问
    算法学习笔记:关联分析(转)
    Python查看模块信息
    R语言中的因子
  • 原文地址:https://www.cnblogs.com/JansXin/p/7461800.html
Copyright © 2011-2022 走看看