Python——while、continue、break、while-else、or、and、not


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

 


免責聲明!

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



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