1. while
終止while循環:
(1) 改變條件,使其不成立
(2) break
應用實例1:計算1+2+3+...+100
#1.使用兩個變量 count = 1 sum = 0 while count <= 100: sum = sum + count count = count + 1 print(sum) #5050 #2.使用三個變量 count = 1 sum = 0 flag = True while flag: sum = sum + count count = count + 1 if count > 100: flag = False print(sum)
應用實例2:打印1-100
#1.使用兩個變量 count = 1 flag = True while flag: print(count) count = count + 1 if count > 100: flag = False #2.使用一個變量 count = 0 while count <= 100: print(count) count = count + 1
2. continue
結束本次循環,繼續下一次循環
#一直循環輸出1
count = 1 while count < 20: print(count) continue count = count + 1
3. break
print('11') while True: print('222') print(333) break print(444) print('abc')
應用實例:打印1-100
count = 1 while True: print(count) count = count + 1 if count > 100:break
4. while-else
(1)while循環被break打斷,則不執行else
(2)while循環未被break打斷,則執行else
count = 0 while count <= 5: count += 1 if count == 3: break #(1)不執行else,如下左圖 #pass #(2)執行else,如下右圖 print('loop',count) else: print('循環正常執行結束')


5. 邏輯運算符or_and_not

(1)x or y
若x為真,返回x(0為假,其余為真);否則返回y
print(1 or 2) #1 print(1 or 5) #1 print(0 or 1) #1 print(0 or 2) #2
(2)x and y(結果與or相反)
若x為真,返回y(0為假,其余為真);否則返回x
print(1 and 2) #2 print(1 and 5) #5 print(0 and 1) #0 print(0 and 2) #0
(3)not x
若x為真,返回True;否則返回False
print(not 0) #True print(not 1) #False print(not 56) #False
