1. 程式人生 > >Python流程控制與while 迴圈(day01)

Python流程控制與while 迴圈(day01)

一:流程控制

假如把寫程式比做走路,那我們到現在為止,一直走的都是直路,還沒遇到過分叉口,想象現實中,你遇到了分叉口,然後你決定往哪拐必然是有所動機的。你要判斷哪條叉路是你真正要走的路,如果我們想讓
程式也能處理這樣的操作,那麼設一些條件判斷語句,滿足哪個條件,就執行相對應的操作。

單分支

if  條件:
   滿足條件執行後的程式碼

如:if  a > b:
          print(“hello”)

雙分支

if  條件:
    滿足條件執行後的程式碼
else: 
     不滿足條件執行的程式碼

如: 
if   a > b:
     print("hello")
else:
     print("no")

多重分支判斷:

if    條件1:
       滿足條件1執行的程式碼:
elif  條件2:
        滿足條件2執行的程式碼:
elif  條件3:
      滿足條件3執行的程式碼:
        
else:
      以上條件都不滿足執行的程式碼

如:
grade = int(input("請輸入成績: "))

if    grade == 100:
      print("S")
elif  grade >= 90:
       print("A")
elif  grade >= 80:
       print("B")
elif   grade >= 70:
       print("C")
else:
        print("D")

多重條件判斷

兩個條件都滿足
if     條件1   and  條件2:
       兩者都滿足後執行的條件
如:

if    a  > b and a <=c:
      print("hello")

兩個條件二選一
if     條件1   or  條件2:
       兩者只要滿足一個條件都會執行
如:

if    a  > b or a <=c:
      print("hello")

注:if 可以多重巢狀,注意每層之間的縮排。

二: while迴圈

通過迴圈語句可以讓程式碼重複執行多次,while 指當後面的條件成立,就執行while下面的程式碼

格式:

定義一個計數器,
count = 0 

while 條件:
         滿足條件後執行的程式碼

注:這裡的條件可以為 count <3 也可以為True,代表為真,下方的程式碼會一直執行

如:
我們讓程式從 0 列印到100
count = 0

while  count <=100:
          print("loop",count)
          count +=1         每執行一次,就把count+1,要不然就變成死迴圈了,因為count一直為0

列印1到100的偶數

注:能被2整除的都是偶數
count = 0 

while  count <=100:
           if  count %2 = 0:
               print("loop",count)
            count += 1

迴圈中止語句
如果在迴圈的過程中,因為某些原因,你不想繼續執行迴圈了,怎麼把他中止呢?這就用到break 或 continue語句:

break : 完全結束一個迴圈,跳出迴圈體執行迴圈後面的語句
continue: 與break類似,區別在於continue 只是終止本次迴圈,接著還執行後面的迴圈,break則完全終止。
sleep : 讓程式睡眠 n秒後再執行

例子:

count = 0
 
while count <=100:
         print("loop",count)
         if  count == 5:
              break
         count +=1

當count = 5的時候,迴圈將會結束

例子2:

count = 0
while count <= 100:
         count +=1
         if  count > 5  and count <95:
             continue
         print("loop",count)
print("----out of while loop----")

只有count 在 6-94之間,就不走下面的print語句,直接進入下一次loop。
while 還有一種語句

while 條件:
執行的程式碼:
else:
迴圈執行完後執行的語句

注: 當迴圈被break後,就不會執行else 處的語句。