if判斷、while循環、for循環


一. if判斷

基本結構:

if 執行語句1
   print(代碼塊1);
print(代碼塊2);

# 滿足執行語句1時,執行代碼塊1和代碼塊2,否則只執行代碼塊2.
if 執行語句1
   print(代碼塊1);
 else
   print(代碼塊2);

# 滿足執行語句1條件,執行代碼塊1.否則執行代碼塊2.

 

 if 執行語句1
   print(代碼塊1);
 elif 執行語句2
   print(代碼塊2);

 ......
 elif 執行語句n
   print(代碼塊n);

# 當滿足執行語句1時,執行代碼塊1.不滿足執行語句1滿足執行語句2時,執行代碼塊2........不滿足執行語句n-1滿足執行語句n時,執行代碼塊n.

 

if 執行語句1
   print(代碼塊1);
  if 執行語句2
    print(代碼塊2);
    else:  
      print(代碼塊3);
 else:
      print(代碼塊4);

# 當只足執行語句1時,執行代碼塊1.不滿足執行語句1時,執行代碼塊4.
# 當滿足執行語句1且滿足執行語句2時,執行代碼塊2,否則執行代碼塊3

 二. while循環

結構:
        while 條件:
            代碼塊(循環體)

執行流程:判斷條件真假,真則執行代碼塊. 再次判斷條件是否為真,若為真執行代碼塊.   .......直到條件為假時,跳出循環.

break    停止當前本層循環

continue  結束當前本次循環, 繼續執行下一次循環
count = 0
while count < 10:
    count = count + 1
    print(count)#輸出從1到10這10個數字
#輸出1 2 3 4 5 6  8 9 10
count = 0
while count < 10:
    count = count + 1
    if count == 7:       
        continue #跳出本次循環,進入下一次循環
    print(count)
if s == 'q':
  break   # 停止當前循環

 

三. for循環

語法: 
for 變量 in 可迭代對象            # 將對象里的每個字符都賦給變量
    循環體
else:
for i in range(10)
    if i == 8:
        print('888')
else:
    print('not found')

四. 格式化輸出

        %s: 字符串的占位符, 可以放置任何內容(數字)

       %d: 數字的占位符

1 count = 1
2 print("次數為%s次" % (count))

 

 

 

 


免責聲明!

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



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