《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()

 


免責聲明!

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



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