司法三等申論題
108年
[檢察事務官電子資訊組] 程式語言
第 二 題
📖 題組:
請問下列兩個 Python 程式,若分別輸入 Andy, World, Everyone 後:
程式 A
1 import sys
2
3 def Calc(sInput):
4 sOutput = "Hello, " + sInput + "!"
5 return(sOutput)
6
7 sInput = sys.stdin.readline()
8 while (sInput != ""):
9 sInput = sInput.replace("\r", "").replace("\n", "")
10 print(Calc(sInput))
11 sInput = sys.stdin.readline()
程式 B
1 def Calc(sInput):
2 sOutput = "Hello, " + sInput + "!"
3 return(sOutput)
4
5 try:
6 while(1):
7 print(Calc(input()))
8 except (EOFError):
9 pass
請問下列兩個 Python 程式,若分別輸入 Andy, World, Everyone 後:
程式 A
1 import sys
2
3 def Calc(sInput):
4 sOutput = "Hello, " + sInput + "!"
5 return(sOutput)
6
7 sInput = sys.stdin.readline()
8 while (sInput != ""):
9 sInput = sInput.replace("\r", "").replace("\n", "")
10 print(Calc(sInput))
11 sInput = sys.stdin.readline()
程式 B
1 def Calc(sInput):
2 sOutput = "Hello, " + sInput + "!"
3 return(sOutput)
4
5 try:
6 while(1):
7 print(Calc(input()))
8 except (EOFError):
9 pass
📝 此題為申論題,共 2 小題
小題 (二)
若兩個程式都可以被正常執行,請說明其執行方式與優缺點?(15 分)
思路引導 VIP
看到此題,應先辨識兩段程式碼的核心差異在於「I/O 處理機制」與「控制流程(Control Flow)設計」。程式 A 透過底層標準輸入串流(sys.stdin)與明確的條件判斷來控制迴圈;程式 B 則使用內建高階函式(input)搭配例外處理(Exception Handling)來終止程式。解題時應從執行機制、可讀性與執行效能(Overhead)三個維度進行剖析。
小題 (一)
其執行後的輸出分別為何?(10 分)
思路引導 VIP
面對程式碼追蹤題,應先辨別 I/O 串流讀取機制與迴圈終止條件(如 readline() 的空字串判定與 input() 的例外捕捉)。接著細部追蹤字串處理邏輯,特別注意換行字元(Newline)的保留與過濾行為,即可精確推導出終端機輸出。