論壇程式碼好讀版:https://forum.community.tw/t/topic/475
順便再宣傳一下 community.tw,最近在舉辦抽獎活動,詳情見論壇內的置頂活動內容
這是一個無廣告的論壇,自動程式碼著色、上標籤等,方便大家分享程式碼討論
也避免用貼圖片的方式,這樣之後也比較容易搜尋到,詳情可見 #1Yukoxd2
本文開始
>>> a = 5
>>> if a == 5:
... print("a is 5")
... else:
... print("a is not 5")
... print("if-else end")
先猜猜看,在 python interactive mode 這樣會不會正常執行呢?
答案是會跳出 SyntaxError: invalid syntax 錯誤
找了一下資料,Stack Overflow: read eval print loop - Why am I getting an invalid syntax error in Python
REPL right after IF statement?
這裡有提到
The body of the loop is indented: indentation is Python’s way of grouping
statements. At the interactive prompt, you have to type a tab or space(s) for
each indented line. In practice you will prepare more complicated input for
Python with a text editor; all decent text editors have an auto-indent
facility. When a compound statement is entered interactively, it must be
followed by a blank line to indicate completion (since the parser cannot
guess when you have typed the last line). Note that each line within a basic
block must be indented by the same amount.
有清楚指出在 interactive mode 一定要用空白行作為最後一個區塊的結束
但這只有限制在最後一個區塊,所以多用函數包住,就可以讓 print 直接在 if 結束之
後使用,但函數結束後還是只能空白行結束;以及限制在interactive mode,所以在
jupyter notebook 或者寫成 python 檔案,上面的程式碼都不會出錯。