《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()
原文地址:https://www.cnblogs.com/zsh-blogs/p/10005428.html