《Python程式設計(第3版)》[美] 約翰·策勒(John Zelle) 第 2 章 答案
判斷對錯
1.編寫程式的好方法是立即鍵入一些程式碼,然後除錯它,直到它工作。
2.可以在不使用程式語言的情況下編寫演算法。
3.程式在寫入和除錯後不再需要修改。
4.Python 識別符號必須以字母或下劃線開頭。
5.關鍵詞是好的變數名。
6.表示式由文字、變數和運算子構成。
7.在 Python 中,x = x + 1 是一個合法的語句。
8.Python 不允許使用單個語句輸入多個值。
9.計數迴圈被設計為迭代特定次數。
10.在流程圖中,菱形用於展示語句序列,矩形用於判斷點。
解答
1、F [說明:p.17 “編寫大型程式是一項艱鉅的挑戰。如果沒有系統的方法,幾乎是不可能的。“,”建立程式的過程通常被分成幾個階段,依據是每個階段中產生的資訊。”,p.18 “SusAn 知道,好是先弄清楚她希望構建什麼,而不是一頭鑽進去開始程式設計。”]2、T [說明:p.18 “SusAn 可以用一種計算機語言來寫她的演算法。然而,正式將它寫出來需要相當的精度, 這常常會扼殺開發演算法的創造性過程。作為替代,她用“虛擬碼”編寫演算法。虛擬碼只是精確的英語,描述了程式做的事。這意味著既可以交流演算法,又不必讓大腦承擔額外的開銷,正確寫出某種特定程式語言的細節”] 3、F [說明:p.17 “維護程式 繼續根據使用者的需求開發該程式。大多數程式從來沒有真正完成,它們在多年的使用中不斷演進。”] 4、T [說明:p.19 “Python 對識別符號的構成有一些規則。每個識別符號必須以字母或下劃線(“_”字元)開頭,後跟字母、數字或下劃線的任意序列。這意味著單個識別符號不能包含任何空格。”]5、F [說明:p.20 “需要注意一件重要的事情:一些識別符號是 Python 本身的一部分。這些名稱稱為“保留字”或“關鍵字”,不能用作普通識別符號。”] 6、T(這題中的“文字”的原文是“literAls”,其實就是“字面量”) [說明:p.20 “最簡單的表示式是字面量。”,p.21 “一個簡單的識別符號也可以是一個表示式。我們使用識別符號作為變數來給名字賦值。當識別符號作為表示式出現時,它的值會被取出,作為表示式的結果。”,“較複雜、較有趣的表示式可以通過組合較簡單的表示式和操作符來構造。”] 7、T [說明:p.23-24 “有時,將變數看作計算機記憶體中的一種命名的儲存位置是有幫助的,我們可以在其中放入一個值。當變數更改時,舊值將被刪除,並寫入一個新值。圖 2.1 展示了用這個模型來描繪 x = x + 1 的效果。這正是賦值在某些計算機語言中工作的方式。這也是檢視賦值效果的一種非常簡單的方式,你會在整本書中看到類似這樣的圖片。”] [有趣的是:在函數語言程式設計語言(例如:RACket)中,這是不合法的。]8、F [說明:p.26 “有一個賦值語句的替代形式,允許我們同時計算幾個值。它看起來像這樣: <vAr1>, <vAr2>, ..., <vArn> = <expr1>, <expr2>, ..., <exprn> ,這稱為“同時賦值”。”] 9、T [說明:p.27 “簡單的迴圈稱為“確定迴圈”。 這是會執行一定次數的迴圈。也就是說,在程式中迴圈開始時,Python 就知道迴圈(或“迭 代”)的次數。”,“這個特定的迴圈模式稱為“計數迴圈”,它用 Python 的 for 語句構建。”] 10、F(下面這句話中“決定”的原文是“DeCision”,其實就是“判斷點”) [說明:p.29 “流程圖中的菱形框表示程式中的決定。”]
多項選擇
1.以下________________項不是軟體開發過程中的一個步驟。
A.規格說明
B.測試/除錯
C.決定費用
D.維護
2.將攝氏度轉換為華氏度的正確公式是________________。
A. F = 9/5© + 32
B.F = 5/9© − 32
C. F = B2 − 4AC
D .F = (212 – 32)/(100 – 0)
3.準確描述計算機程式將做什麼來解決問題的過程稱為________________。
A.設計
B .實現
C.程式設計
D.規格說明
4.以下________________項不是合法的識別符號。
A.spAm
B.spAm
C.2spAm
D.spAm4U
5.下列________________不在表示式中使用。
A.變數
B .語句
C.操作符
D.字面量
6.生成或計算新資料值的程式碼片段被稱為________________。
A.識別符號
B.表示式
C.生成子句
D.賦值語句
7.以下________________項不是 IPO 模式的一部分。
A.輸入
B .程式
C .處理
D .輸出
8.模板 for <vAriABle> in rAnge(<expr>) 描述了________________。
A.一般for迴圈
B.賦值語句
C.流程圖
D.計數迴圈
9.以下________________項是準確的 Python 賦值模型。
A.貼上便籤
B.變數盒子
C.同時
D.塑料尺
10.在 Python 中,獲取使用者輸入通過一個特殊的表示式來實現,稱為________________。
A.for
B .reAD
C.同時賦值
D.input
解答
1 C 2 A 3 D 4 C 5 B 6 B 7 B 8 D 9 A 10 D
討論
1.列出並用你自己的語言描述軟體開發過程中的六個步驟。
解答
首先,必須儘可能準確地理解問題。這是最重要的一步,因此可能需要大量的研究和思考。而事實上,這個步驟可能比所有其他步驟花費更長的時間。沒有這一步,就不可能繼續其他的步驟。換句話說,這一步驟需要通常所說的“分析”。但是我們真正在這裡談論的,是以精確和明確的方式定義(或描述)問題。對問題的真正定義(或描述)是下一步的關鍵。換句話說,這一步回答了這樣一個問題:問題是什麼? 其次,只有在定義(或描述)問題之後,才能開始考慮可以採取哪些措施來解決問題。在程式設計的背景下,意味著決定(並描述)您的程式將如何解決您定義(或描述)的問題。更準確地說,它意味著定義(或描述)程式的輸入和輸出將是什麼。他們的描述應該包括他們彼此之間的關係。程式的真正定義(或描述,包括輸入與輸出的關係)是下一步的關鍵。換句話說,這一步回答了這個問題:問題解決方案的規格說明是什麼? 第三,在描述了響應問題描述的程式之後,就要描述程式本身的結構。這意味著設計將滿足上述規格說明的逐步過程(也稱為演算法)。換一種說法,這一步回答了這個問題:為了滿足規格說明,該程式應該如何設計? 第四,在決定適當的演算法設計之後,是時候通過將設計轉換成程式語言並將其放入計算機來實現它,以便計算機可以遵循指令。換句話說,這一步回答了這個問題:應該如何將程式設計轉化為程式碼? 第五,在演算法實現完成後,需要驗證程式是否按預期工作,即根據步驟 2 中的規格說明。這可以看作是一個反饋迴圈,通過該迴圈來測試程式的錯誤。如果出現錯誤,必須在稱為”除錯“的過程中處理這些錯誤。換句話說,這一步回答了這個問題:什麼會破壞程式? 第六,隨著時間的推移,必須維護該程式以響應使用者需求。因此,隨著使用者習慣和期望的發展,程式需要進一步發展。換句話說,此步驟要求改程序序,從而重複步驟 1 到步驟 5 ,其中步驟 1 中的問題將被定義為使用者需求的變化。
2.寫出 chaos.py 程式(第 1.6 節),並識別程式的各部分如下:
- 圈出每個識別符號。
- 為每個表示式加下劃線。
- 在每一行的末尾添加註釋,指示該行上的語句型別(輸出、賦值、輸入、迴圈等)。
解答
1 # File: chaos.py 2 # A simple program illustrating chaotic behavior. 3 def main(): # 函式定義 4 print("This program illustrates a chaotic funciton.") # 輸出語句 5 x = eval(input("Enter a number between 0 and 1: ")) # 包含了輸入語句的賦值語句 6 for i in range(10): # 迴圈語句 7 x = 3.9 * x * (1 - x) # 表示式 8 print(x) # 輸出語句
- 識別符號 chaos, main(), print(), x, eval(), input(), for, i, in, range()
- 表示式 字面量:“This program illustrates a chaotic funciton.”, “Enter a number betwee 0 and 1”, 10, 3.9 使用運算子:3.9 * x * (1 - x) 使用迴圈:for i in range(10)——從技術層面來講,這其實是一個控制結構,但是它生成了新的值(一個從 0 到 9 的列表),所以我把它當作表示式
3.解釋確定迴圈、for 迴圈和計數迴圈幾個概念之間的關係。
解答
確定迴圈是最簡單的迴圈,它將在迴圈開始前定義迴圈體要迴圈的次數。 計數迴圈是一種特定的迴圈模式。它使用確定迴圈的常用方法。迴圈體將根據定義的計數或次數來迴圈。 for 迴圈是 Python 中的一個語句,用於實現計數迴圈,並有著這y的形式:
for <var> in <sequence>: <body> ```
4、顯示以下片段的輸出:
a.for i in range(5): print(i * i) b.for d in [3,1,4,1,5]: print(d, end=" ") c.for i in range(4): print("Hello") d.for i in range(5): print(i, 2**i)
解答
a. 0 1 4 9 16 b. 3 1 4 1 5 c. Hello Hello Hello Hello d. 0, 1 1, 2 2, 4 3, 8 4, 16 5, 32
5.先寫出一個演算法的虛擬碼而不是立即投入 Python 程式碼,為什麼是一個好主意?
解答
這減少了讓大腦承擔的額外的開銷。用一種計算機語言以相當精度來寫演算法,通常會扼殺開發演算法的創造性過程。(詳見 p.18)
6.除 end 之外,Python 的 print 函式還支援其他關鍵字引數。其中一個關鍵字引數 是sep。你認為sep引數是什麼?(提示:sep是分隔符的縮寫。通過互動式執行或通過 查閱 Python 文件來檢驗你的想法)。
sep 引數用以指定在列印時將多個值分割的分隔符。
7.如果執行下面的程式碼,你認為會發生什麼?
print("start") for i in range(0): print("Hello") print("end")
看看本章的 for 語句的流程圖,幫助你弄明白。然後在程式中嘗試這些程式碼,檢驗你的預測。
解答
輸出為: start end 顯然,輸出中並沒有 Hello,即迴圈體並沒有執行。根據第 29 頁的流程圖,由於 range(0) 定義的序列中沒有其他項,因此迴圈體永遠不會被執行。 [參考:p.28 ”一般來說,range(<expr>) 將產生一個數字序列,從 0 開始,但不包括 <expr> 的值。如果你想一想,就會發現表示式的值確定了結果序列中的項數。“]
程式設計練習
1.一個使用者友好的程式應該列印一個介紹,告訴使用者程式做什麼。修改 convert.py 程式(第 2.2 節),列印介紹。
解答
1 # convert.py 2 # A program to convert Celsius temps to Fahrenheit 3 # by: Susan Computewell 4 5 def main(): 6 print("This program coverts a temperature in Celsius to a temperature in Fahrenheit.") 7 8 celsius = eval(input("What is the Celsius temperature? ")) 9 fahrenheit = 9/5 * celsius + 32 10 11 print("The temperature is", fahrenheit, "degrees Fahrenheit.") 12 13 main()
2.在許多使用 Python 的系統上,可以通過簡單地點選(或雙擊)程式檔案的圖示來執行程式。如果你能夠以這種方式執行 convert.py 程式,你可能會發現另一個可用性問題。程式在新視窗中開始執行,但程式一完成,視窗就會消失,因此你無法讀取結果。在程式結束時新增一個輸入語句,讓它暫停,給使用者一個讀取結果的機會。下面這樣的程式碼應該有效:input("Press the <Enter> key to quit.")
解答
1 # convert.py 2 # A program to convert Celsius temps to Fahrenheit 3 # by: Susan Computewell 4 5 def main(): 6 print("This program coverts a temperature in Celsius to a temperature in Fahrenheit.") 7 8 celsius = eval(input("What is the Celsius temperature? ")) 9 fahrenheit = 9/5 * celsius + 32 10 11 print("The temperature is", fahrenheit, "degrees Fahrenheit.") 12 13 input("Press the <Enter> key to quit.") 14 15 main()
3、修改 avg2.py 程式(第 2.5.3 節),找出三個考試成績的平均值。
解答
1 # avg3.py 2 # A simple program to average three exam scores 3 # Illustrates use of multiple input 4 5 def main(): 6 print("This program computes the average of three exam scores.") 7 8 score1, score2, score3 = eval(input("Enter three scores separated by a comma: ")) 9 average = (score1 + score2 + score3) / 3 10 11 print("The average of the three scores is:", average) 12 main()
4.使用迴圈修改 convert.py 程式(第 2.2 節),讓它在退出前執行 5 次。每次通過 迴圈,程式應該從使用者獲得另一個溫度,並列印轉換的值。
解答
1 # convert.py 2 # A program to convert Celsius temps to Fahrenheit five times 3 # by: Susan Computewell 4 5 def main(): 6 for i in range(5): 7 celsius = eval(input("What is the Celsius temperature? ")) 8 fahrenheit = 9/5 * celsius + 32 9 10 print("The temperature is", fahrenheit, "degrees Fahrenheit.") 11 12 main()
5.修改 convert.py 程式(第 2.2 節),讓它計算並列印一個攝氏溫度和華氏度的對應表,從 0℃到 100℃,每隔 10℃一個值。
解答
1 #converstionchart.py 2 # A program to compute and print a table of Celsius temperatures and the Fahrenheit equivalents every 10 degrees 3 # from 0 degrees celsius to 100 degrees celsius 4 5 def main(): 6 print("Celisus Temperatures and") 7 print("Their Fahrenheit Equivalents") 8 print("{0:<14}{1:<14}".format("C", "F")) 9 print("----------------------------") 10 11 for i in range(11): 12 celsius = 10 * i 13 fahrenheit = int(9/5 * celsius + 32) 14 15 print("{0:<14}{1:<14}".format(celsius, fahrenheit)) 16 17 main()
6.修改 futval.py程式(第 2.7 節),讓投資的年數也由使用者輸入。確保更改後的訊息,以反映正確的年數。
解答
1 # futval.py 2 # A program to compute the future value of an investment 3 # with number of years determined by the user 4 5 def main(): 6 print("This program calculates the future value") 7 print("of a multi-year investment with") 8 print("non-compounding interest.") 9 10 principal = eval(input("Enter the initial principal: ")) 11 apr = eval(input("Enter the annual interest rate: ")) 12 years = eval(input("Enter the number of years for the investment: ")) 13 14 for i in range(years): 15 principal = principal * (1 + apr) 16 17 print("The value in ", years ,"years" "is:", principal) 18 19 main()
7.假設你有一個投資計劃,每年投資一定的固定金額。修改 futval.py,計算你的投資的總累積值。該程式的輸入將是每年投資的金額、利率和投資的年數。
解答
1 # futval.py 2 # A program to compute the future value of an investment 3 # with number of years determined by the user 4 5 def main(): 6 print("This program calculates the total future value") 7 print("of a multi-year investment with") 8 print("non-compounding interest and an additional") 9 print("investment of a certain fixed amount each year.") 10 11 principal = eval(input("Enter the initial principal: ")) 12 apr = eval(input("Enter the annual interest rate: ")) 13 yearlyinvestment = eval(input("Enter the fixed yearly amount to invest: ")) 14 years = eval(input("Enter the number of years for the investment: ")) 15 16 for i in range(years): 17 principal = principal + yearlyinvestment 18 principal = principal * (1 + apr) 19 20 print("The value in", years, "years", "is:", principal) 21 22 main()
這裡假設第一年除了本金之外,還投資了每年一定的固定金額。
8.作為 APR 的替代方案,賬戶所產生的利息通常通過名義利率和複利期數來描述。例如,如果利率為 3%,利息按季度計算複利,則該賬戶實際上每 3 個月賺取 0.75%的利息。 請修改 futval.py 程式,用此方法輸入利率。程式應提示使用者每年的利率(rate)和利息每年複利的次數(periods)。要計算 10 年的價值,程式將迴圈 10 * periods 次,並在每次迭代中累積 rate/period 的利息。
解答
1 # futval.py 2 # A program to compute the future value of an investment 3 # with number of years determined by the user 4 5 def main(): 6 print("This program calculates the total future value") 7 print("of a multi-year investment with by describing") 8 print("the interest accrued in terms of a nominal rate") 9 print("and the number of compounding periods.") 10 11 principal = eval(input("Enter the initial principal: ")) 12 interestrate = eval(input("Enter the interest rate: ")) 13 periods = eval(input("Enter the number of compounding periods per year: ")) 14 years = eval(input("Enter the number of years for the investment: ")) 15 16 nominalrate = interestrate / periods 17 18 for i in range(periods * years): 19 principal = principal * (1 + nominalrate) 20 21 print("The value in", years ,"years is:", principal, sep=" ") 22 23 main()
這裡要搞清楚一個概念,名義利率是什麼? 名義利率,是央行或其它提供資金借貸的機構所公佈的未調整通貨膨脹因素的利率,即利息(報酬)的貨幣額與本金的貨幣額的比率。 即指包括補償通貨膨脹(包括通貨緊縮)風險的利率。 實際利率,指物價水平不變,從而貨幣購買力不變條件下的利息率。 名義利率並不是投資者能夠獲得的真實收益,還與貨幣的購買力有關。如果發生通貨膨脹,投資者所得的貨幣購買力會貶值,因此投資者所獲得的真實收益必須剔除通貨膨脹的影響,這就是實際利率。 在這題裡,簡單地算就是:名義利率 = 年利率 / 複利期。
9.編寫一個程式,將溫度從華氏溫度轉換為攝氏溫度。
解答
1 # convert2.py 2 # A program to convert Fahrenheit temps to Celsius 3 # by: Susan Computewell 4 5 def main(): 6 print("This program converts a temperature in Fahrenheit to a temperature in Celsius.") 7 8 fahrenheit = eval(input("What is the Fahrenheit temperature? ")) 9 celsius = (fahrenheit - 32) * 5/9 10 11 print("The temperature is", celsius, "degrees Celsius.") 12 13 main()
由於 F = (9/5)C + 32,經過簡單的等式變換,顯然,C = (F - 32) * 5/9。
10.編寫一個程式,將以千米為單位的距離轉換為英里。1 千米約為 0.62 英里。
解答
1 # convert3.py 2 # A program to convert distances measured in kilometers to miles 3 # by: Susan Computewell 4 5 def main(): 6 print("This program converts distances measured in kilometers to miles.") 7 8 kilometers = eval(input("What is the distance in kilometers?")) 9 miles = kilometers * .62 10 11 print("The distance is", kilometers, "kilometers.") 12 input("Press the <Enter> key to quit.") 13 14 main()
11.編寫一個程式以執行你自己選擇的單位轉換。確保程式列印介紹,解釋它的作用。
解答
1 # convert3.py 2 # A program to convert liters to gallons 3 4 def main(): 5 print("This program converts liters to gallons.") 6 7 gallons = eval(input("How many gallons? ")) 8 liters = gallons * .264172052 9 10 print("The fluid volume in liters is", liters, "liters.") 11 12 input("Press the <Enter> key to quit.") 13 14 main()
1 加侖 = 0.264172052 升
12.編寫一個互動式 Python 計算器程式。程式應該允許使用者鍵入數學表示式,然後打印表達式的值。加入迴圈,以便使用者可以執行許多計算(例如,多 100 個)。注意:要提前退出,使用者可以通過鍵入一個錯誤的表示式,或簡單地關閉計算器程式執行的視窗,讓程式崩潰。在後續章節中,你將學習終止互動式程式的更好方法。
解答
1 def main(): 2 print("This program is an interactive calculator. Enter your calculations below.") 3 4 for i in range(100): 5 expression = eval(input("")) 6 print(expression) 7 8 main()