if...while循環
阿新 • • 發佈:2017-07-18
print python num span div cnblogs 布爾值 一樣在 ted
一.if語句
功能:希望電腦像人腦一樣在不同的條件下,做出不同的反應。
語法:
執行代碼
1.第一種
1 a = 1 2 b = 2 3 if a > b and (a/b > 0.2): 4 print(‘yes‘) 5 else: 6 print(‘no‘)
2.第二種
1 num = 5 2 if num == 3: 3 print ‘boss‘ 4 elif num == 2: 5 print ‘user‘ 6 elif num == 1: 7 print ‘worker‘ 8 elif num < 0: 9 print ‘error‘ 10 else: 11 print ‘roadman‘
3.第三種
NUM = 7 if NUM > 6 or NUM >4: print(‘ok‘)
註意:1.一個if判斷只能有一個else,else代表if判斷的終結
2.條件可以引入運算符:not,and,or,is,is not
3.下列對象的布爾值都是False
二.while語句
基本形式
while 判斷條件:
執行語句……
例子:
1 #!/usr/bin/python 2 3 count = 0 4 while (count < 9): 5 print ‘The count is:‘, count 6 count = count + 1 7 print "Good bye!"
while 語句時還有另外兩個重要的命令 continue,break 來跳過循環,continue 用於跳過該次循環,break 則是用於退出循環,此外"判斷條件"還可以是個常值,表示循環必定成立,具體用法如下:
1 # continue 和 break 用法 2 3 i = 1 4 while i < 10:5 i += 1 6 if i%2 > 0: # 非雙數時跳過輸出 7 continue 8 print i # 輸出雙數2、4、6、8、10 9 10 i = 1 11 while 1: # 循環條件為1必定成立 12 print i # 輸出1~10 13 i += 1 14 if i > 10: # 當i大於10時跳出循環 15 break
在 python 中,while … else 在循環條件為 false 時執行 else 語句塊:
1 #!/usr/bin/python 2 3 count = 0 4 while count < 5: 5 print count, " is less than 5" 6 count = count + 1 7 else: 8 print count, " is not less than 5" 9 #輸出結果 10 0 is less than 5 11 1 is less than 5 12 2 is less than 5 13 3 is less than 5 14 4 is less than 5 15 5 is not less than 5
無限循環:
count=0 while True: print(‘the loop is %s‘ %count) count+=1
tag=True count=0 while tag: if count == 9: tag=False print(‘the loop is %s‘ %count) count+=1
if...while循環