文章目錄
本單元測驗:
1. 敘述 (Statement)
1.1 常見敘述種類
敘述 (Statement) 指的是 Python 直譯器可以執行的代碼單元。其敘述種類主要常見有下面四種:
- 指派敘述 (assignment statement):例如 a = 1
- 輸出敘述(print statement):例如 print(a)
- 條件敘述 (Conditional statement):例如 if 敘述
- 迴圈敘述 (Looping statement):例如 for 敘述、while 敘述
其中 if 敘述、for 敘述、while 敘述及其他等不同敘述,我們可以先看下面範例練習一下,詳細內容則會在後面文章介紹。
範例 1:指派敘述及輸出敘述
範例 2:if 敘述
範例 3:for 敘述
範例 4:while 敘述
1.2 多行敘述 (Multi-line statement)
範例 5:我們可以使用 \ 擴展多行敘述
範例 6:括號( )、中括號[ ] 或大括號 { }都明確表示多行敘述的意思
範例 7:使用分號 ; 將多行敘述放在一行中
2. 縮排 (Indentation)
縮排 (Indentation)是指代碼行最前面開頭的空格。在其他程式語言中,代碼中的縮排 (Indentation)通常只是為了便於閱讀,然而在 Python 中的縮排 (Indentation)卻是非常重要。
Python 使用縮排 (Indentation)來表示代碼區塊,如果你跳過縮排 (Indentation),Python 會給你一個錯誤。
範例 8:該縮排而未縮排時(例如 for 敘述下的區塊),結果將會產生錯誤
範例 9:調整縮排後就 👌 了
範例 10:該縮排而未縮排時(例如 if 敘述下的區塊),結果將會產生錯誤
範例 11:調整縮排後也一樣 👌 了
3. 註解 (Comments)
- 每個程式語言都有註解的需求
- 註解不僅是可幫助自己了解程式相關細節,也方便其他人一起參與開發及維護
- 在 Python 中,我們使用 # 符號開始編寫註解
- 在 Python 中執行程式時,不會執行 # 後面的註解文字
3.1 單行註解 (Single-line Comment)
範例 12:單行註釋 – 使用
3.2 多行註解 (Multi-line Comments)
範例 13:多行註釋 – 使用
範例 14:多行註釋 – 使用 ”’ 或 “””
當我們使用關鍵字 True 來當作變數時,系統將會出現語法錯誤 (SyntaxError) 訊息,提醒不能將值指定 (assign) 給關鍵字。
經由本篇文章介紹後,相信初學者對 Python 的敘述 (Statement)、縮排 (Indentation) 及註解 (Comments)已有基本認識,後續會持續分享 Python 相關學習文章給有興趣的初學者。
4. Python 練習
學習環境:Google Colab (學習請按我)
練習範例:有 (本文提供)
Quiz:有 (測驗請按我)
如果你喜歡這篇文章歡迎訂閱、分享(請載名出處)與追蹤,並持續關注最新文章。同時 FB 及 IG 也會不定期提供國內外教育與科技新知。
【Python for Beginner 系列文章】
Python for Beginners (1)|Python 介紹及相關開發環境簡介
Python for Beginners (2)|變數 (Variables) 及關鍵字 (Keywords)
Python for Beginners (3)|敘述 (Statement)、縮排 (Indentation) 及註解 (Comments)
Python for Beginners (4)|運算子 (Operators)、輸入 (Input)、輸出 (Output)及 import 簡介
Python for Beginners (5)|各類運算子 (Operators) 詳細介紹與使用
Python for Beginners (6)|數值 (Numeric) 資料型態介紹與使用
Python for Beginners (7)|字串 (String) 資料型態介紹與使用
Python for Beginners (8)|布林 (Boolean) 資料型態介紹與使用
Python for Beginners (9)|串列 (List) 資料型態介紹與使用
Python for Beginners (10)|元組 (Tuple) 資料型態介紹與使用
Python for Beginners (11)|集合 (Set) 資料型態介紹與使用
Python for Beginners (12)|字典 (Dictionary) 資料型態介紹與使用
Python for Beginners (13)|條件判斷式 – if 相關敘述及使用
Python for Beginners (14)|迴圈控制 – while loops
Python for Beginners (15)|迴圈控制 – for loops
Python for Beginners (16)|函式 (Functions)
Python for Beginners (17)|模組 (Module)及套件(Package)
Python for Beginners (18)|檔案處理 (File Handling)