標籤:src hide 區別 log count continue 執行 orm 執行個體
一、while迴圈,continue、break語句在while迴圈中的使用
1、while迴圈語句:
while 條件:
代碼塊
執行過程:判斷條件是否為真,如果為真,執行代碼塊,繼續下次迴圈,繼續判斷條件真假;如果條件為假,結束當前迴圈。
代碼1:
while True: print(‘Hello world‘)
View Code
執行上述代碼,程式會持續運行。在實際編程時,很少使用。
代碼2:
count = 1while count <=10: print(count) count += 1
View Code
執行上述代碼,會輸出1到10。在實際編程中,這種方式經常使用。
舉個一般的栗子:
執行代碼 -> 判斷條件 -> 條件為真,執行迴圈體(迴圈體中一般會有操作、改變判斷條件用到的元素--改變初始值,True變為False等)--> 判斷條件有變化 --> 判斷條件變為假 --> 跳出當前迴圈(本層迴圈)
2、continue語句
設想有這樣一種需求,迴圈輸出數字1至數字10中的偶數,該怎麼實現?此時continue語句就派上用場了
程式碼片段:
count = 1while count <= 10: if count % 2 == 1: # 對2取餘為1,即為奇數,執行if語句對應的代碼塊 count += 1 continue print(count) count += 1
執行結果:
246810[Finished in 0.0s]
continue語句作用:結束本次迴圈,繼續下次迴圈。
即:如果執行到了continue語句,那麼以上代碼中的print(count) count+=1這兩個語句不會執行,會繼續下次迴圈,即跳到while後的count <= 10處,繼續做判斷。
3、break語句
再設想有這樣一個簡單的需要,讓使用者輸入登入使用者名稱,如果輸入的使用者名稱正確,提示有效使用者,退出;如果輸入錯誤,繼續讓使用者輸入登入使用者名稱
程式碼片段:
user_in_db = ‘jason‘while True: user = input(‘Login name:‘) if user == user_in_db: print(‘Valid user name‘) break print(‘這句會執行嗎‘) print(‘Wrong user name, try again‘)print(‘while同級代碼塊‘)
輸出結果:
Login name:jasonValid user namewhile同級代碼塊
從執行結果可以看出,if判斷條件為真,程式執行到break語句,while迴圈體中break的後續語句都沒有執行,跳出while迴圈,執行後續同級代碼塊。
break語句作用:跳出當前迴圈(本層迴圈),不再進行while後的條件判斷,繼續執行後續同級代碼塊。
4、while...else語句
代碼塊1:
count = 1while count <= 5: # if count == 3: # break print(count) count += 1else: print(‘while迴圈正常結束‘)
執行結果:
12345while迴圈正常結束[Finished in 0.0s]
代碼塊2:
count = 1while count <= 5: if count == 3: break print(count) count += 1else: print(‘while迴圈正常結束‘)
執行結果:
12[Finished in 0.0s]
從代碼塊1和代碼塊2的執行結果可以看出,執行到break跳出的迴圈,不會執行else後的語句;正常迴圈結束的,會執行else後的語句。
說明:在 python 中,while … else 表示這樣的意思,while 中的語句和普通的沒有區別,else 中的語句會在迴圈正常執行完(即 while 不是通過 break 跳出而中斷的)的情況下執行,for … else 也是一樣。
二、格式化輸出
%s 字串的預留位置,後邊給的參數是數字也可以
%d 數位預留位置號
程式碼片段:
name = ‘jason‘age = 25print(‘my name is %s‘ % name)
print("i‘m %s years old" % age)print("i‘m %d years old" % age)
輸出結果:
my name is jason
i‘m 25 years oldi‘m 25 years old[Finished in 0.0s]
格式化輸出還有一種format方法,個人也習慣用format的方法去格式化字串,可以自行百度搜尋瞭解一下。
三、Python中的邏輯運算子
(下方來自菜鳥教程,可以點擊下方圖片跳轉)
這裡說明一下這三個運算子的優先順序:not > and > or
下面是練習執行個體,如果能很清楚的算出結果,那麼邏輯運算這塊沒啥大問題。
1) 6 or 2 > 1 2) 3 or 2 > 1 3) 0 or 5 < 4 4) 5 < 4 or 3 5) 2 > 1 or 66) 3 and 2 > 17) 0 and 3 > 18) 2 > 1 and 39) 3 > 1 and 010) 3 > 1 and 2 or 2 < 3 and 3 and 4 or 3 > 2Answer:1)6 or True ==> 6 # 先處理比較子,再處理邏輯運算2)3 or True ==> 33)0 or False ==> False4)False or 3 ==> 35)True or 6 ==> True6)3 and True ==> True7)0 and True ==> 08)True and 3 ==> 39)True and 0 ==> 010)True and 2 or True and 3 and 4 or True -> 2 or 3 and 4 or True ==> 2
------以上是第二天的學習內容------
Python學習-day2