Python学习笔记 - 2.条件执行

常用比较运算符

    x != y # x is not equal to y
    x > y # x is greater than y
    x < y # x is less than y
    x >= y # x is greater than or equal to y
    x <= y # x is less than or equal to y
    x is y # x is the same as y
    x is not y # x is not the same as y

逻辑运算符

逻辑运算符包括and( 与) 、 or( 或) 与not( 非) 三种

条件执行

if语句的末尾用冒号 (:), if语句之后的语句要缩进。(for循环也有相同结构)

语句由一个以冒号( :) 结束的标题行和随后的一个代码缩进区域构成(必须有缩进,否则出错)

    if x > 0 :
             print 'x is positive'

语句块内没有语句的数量限制, 但至少要有一行。使用pass语句, 表示什么也不做(空白语句)。

    if x < 0 :
            pass # need to handle negative values!

如果在Python解释器里输入一个if语句, 提示符会从三个“>”变成三个“.”, 表明正处在一个语句块内, 如下所示:

    >>> x = 3
    >>> if x < 10:
    ... print 'Small'
    ...
    Small
    >>>

分支执行

    if x%2 == 0 :
        print 'x is even'
    else :
        print 'x is odd'

链式条件

    if choice == 'a':
        print 'Bad guess'
    elif choice == 'b':
        print 'Good guess'
    elif choice == 'c':
        print 'Close, but not correct'

嵌套条件

这里省略

try与except异常捕获

你知道程序可能存在问题, 希望在错误发生时增加一些语句, 这时try 和 except就派上用场了。

    inp = raw_input('Enter Fahrenheit                                          Temperature:')
    try:
        fahr = float(inp)
        cel = (fahr - 32.0) * 5.0 / 9.0
        print cel
    except:
        print 'Please enter a number'

Python首先执行try语句块。 如果一切顺利, 它就会跳过except语句块。

逻辑表达式短路评估

    x > = 2 and (x / y)> 2

第一项不满足便不会执行第二项。

守护者模式

除数为零的情况的预先处理

    >>> x = 1
    >>> y = 0
    >>> x >= 2 and y != 0 and (x/y) > 2
    False
    >>> x = 6
    >>> y = 0
    >>> x >= 2 and y != 0 and (x/y) > 2
    False
    >>> x >= 2 and (x/y) > 2 and y != 0
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    ZeroDivisionError: integer division or modulo by zero
    >>>

调试

1.错误类型
2.错误发生位置

空格错误非常棘手, 由于空格和制表符是不可见的, 常常会被忽视。

    >>> x = 5
    >>> y = 6
    File "<stdin>", line 1
    y = 6
    ^
    SyntaxError: invalid syntax

但是实际错误可能会在所显示的代码之前, 有时候还会在前一行。
一般情况下, 错误信息会告诉你问题出现在哪, 但这个出错位置并不准确。

python一行语句中必须所有变量类型相同才能相乘?

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章