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一行語句中必須所有變量類型相同才能相乘?

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