Python 條件、循環、異常處理


一、條件語句

1、布爾值

條件語句中,判斷條件的值一般是布爾值。即條件為真時,將執行什么,條件為假時,將執行什么。

下面的值在作為布爾表達式的時候,會被解釋器看做假(false):

False    None  0   ""   ()    []   {}

注:雖然上面的值被看做是假,但是它們本身並不相等,也就是說None != ()

2、條件語句

a、if語句

b、if....else語句

c、if....elif...elif...else語句

num = input('Enter a number:')
if num>0:
    print 'the number is positive'
elif num<0:
    print 'the number is negative'
else:
    print 'the number is zero'

d、嵌套代碼塊,if....else語句中,if代碼塊中還包含if...else語句之類

二、循環

1、while循環

x = 1
while x <= 5:
    print x
    x += 1

2、for循環

for i in range(4):
    print(i)

 三、跳出循環

一般情況下,循環會一直執行到條件為假,或者到序列元素用完時。但是有些時候可能會提前中斷一個循環,進行新的迭代,或者僅僅就是想結束循環

1、break

2、continue

3、while True/break習語

while true:
    word = raw_input('please enter a word:')
    if not word:break
    print 'the word was '+ words

四、列表推導式

是利用其它列表創建新列表的一種方法。

print([x*x for x in range(5)]) #[0, 1, 4, 9, 16]

 五、異常

1、raise語句,用來引發異常

raise Exception('something is wrong')

2、try..except語句,捕捉異常

3、try..except...except,不止一個except子句

4、try...except () as e,捕捉對象,記錄下錯誤

5、try...except..else..,如果沒有發生異常,執行完try子句后,會執行else子句;

try:
    print 'the right way'
except Exception as e:
    print 'the wrong way'
    print 'return the exception:',e
else:
    print 'continue the right way'
finally:
print 'all continue'

6、try...except..finally..不管異常是否發生,都會執行finally子句;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM