Python语言程序设计(美-梁勇)第5章习题解答(英文)
python程序设计基础课后习题答案(第五章)

第五章答案5.2:实现i s o d d()函数,参数为整数,如果参数为奇数,返回t r u e,否则返回f a l s e。
def isodd(s):x=eval(s)if(x%2==0):return Falseelse:return Truex=input("请输入一个整数:")print(isodd(x))请输入一个整数:5True5.3:实现i s n u m()函数,参数为一个字符串,如果这个字符串属于整数、浮点数或复数的表示,则返回t r u e,否则返回f a l s e。
def isnum(s):try:x=eval(s)if((type(x)==int)|(type(x)==float)|(type(x)==complex)):return Trueelse:return Falseexcept NameError:return Falsex=input("请输入一个字符串:")print(isnum(x))请输入一个字符串:5True题5.4:实现m u l t i()函数,参数个数不限,返回所有参数的乘积。
def multi(x):xlist=x.split(",")xlist = [int(xlist[i]) for i in range(len(xlist))] #for循环,把每个字符转成int值num=1for i in xlist:num=num*iprint(num)s=input("请输入数字,并用,号隔开:")multi(s)请输入数字,并用,号隔开:5,420题5.5:实现i s p r i m e()函数,参数为整数,要有异常处理,如果整数是质数返回t u r e,否则返回f a l s e。
try:def isprime(s):i=2m=0for i in range(2,s-1):if(s%i==0):i+=1m+=1else:i+=1if(m>0):return Falseelse:return Trueexcept NameError:print("请输入一个整数!")s=eval(input("请输入任意一个整数:")) print(isprime(s))请输入任意一个整数:9False。
Python语言程序设计美梁勇第5章习题解答

Python语言程序设计美梁勇第5章习题解答第5章习题解答一、选择题1. 在Python中,下列哪个不是有效的变量名?A. 1nameB. Name1C. _nameD. name_1正确答案:A. 1name2. 下列哪个运算符不是Python的算术运算符?A. +B. *C. /D. %正确答案:D. %3. 在Python中,下列哪个是赋值运算符?A. ==B. >C. +=D. and正确答案:C. +=4. 下列关于列表的描述中,哪个是错误的?A. 列表是一种有序的集合B. 列表可以包含不同的数据类型C. 列表的索引是从0开始的D. 列表可以通过下标修改其中的元素正确答案:B. 列表可以包含不同的数据类型5. 下列关于字典的描述中,哪个是正确的?A. 字典是一种有序的集合B. 字典的每个元素都有一个对应的键和值C. 字典的元素可以通过索引来访问D. 字典中的键必须是字符串类型正确答案:B. 字典的每个元素都有一个对应的键和值二、编程题1. 编写一个函数,接受一个字符串作为参数,返回该字符串的长度。
```pythondef calculate_length(string):return len(string)```2. 编写一个程序,要求用户输入两个数字,并计算它们的和、差、积和商,最后将结果输出。
```pythonnum1 = float(input("请输入第一个数字:"))num2 = float(input("请输入第二个数字:"))add = num1 + num2subtract = num1 - num2multiply = num1 * num2divide = num1 / num2print("两个数字的和:", add)print("两个数字的差:", subtract)print("两个数字的积:", multiply)print("两个数字的商:", divide)```3. 定义一个列表,其中包含5个学生的成绩,计算并输出这5个学生的平均成绩。
Python语言程序设计(美-梁勇)第7章习题解答(英文)

Python语⾔程序设计(美-梁勇)第7章习题解答(英⽂)Chapter 7 Objects and Classes1. See the section "Defining Classes for Objects."2. Define the initializer, create data fields, and define methods.3. Use a constructor4. The name of the initializer is __init__.5. The self refers to the object itself. Through self, themembers of the object can be accessed.6. The syntax for constructing an object isClassName(arguments)The arguments of the constructor match the parametersin the __init__ method without self.The constructor first creates an object in the memoryand then invokes the initializer.7. Initializer is a special method that is called whencreating an object.8.The object member access operator is the dot (.).9.You need to pass an argument in the constructor A() toinvoke the class A’s initializer.10.(a) The constructor should be defined as __init__(self).(b) radius = 3 should be self.radius = 311.count is 100times is 012.count is 0n is 113.__i is a private data field and cannot be accessed fromoutside of the class.14. Correct. The printout is Welcome.15.__on is a private data field and cannot be accessedoutside the class.The way to fix it is to add a getter method for theBoolean property as follows:class A:def __init__(self, on):self.__on = not ondef isOn(self):return self.__ondef main():a = A(False)print(a.isOn())main() # Call the main function16.T wo benefits: (1) for protecting data and (2) for easyto maintain the class.In Python, private data fields are defined with twoleading underscores.17.A dd two underscores as the prefix for the method name.18.S ee the text。
Python语言程序设计(美-梁勇)第3章(英文)习题解答

Chapter 3 Mathematical Functions, Strings, and Objects1.2.True3.r = math.radians(47)4.r = math.degrees(math.pi / 7)5.code = ord('1')code = ord('A')code = ord('B')code = ord('a')code = ord('b')ch = chr(40)ch = chr(59)ch = chr(79)ch = chr(85)ch = chr(90)6.print("\\")print("\"")7.\u00788.D9.2510.title = "chapter " + str(1)11.52312.An object is an entity such as a number, a string, a student, a desk, and a computer. Eachobject has an id and a type. Objects of the same kind have the same type.You can perform operations on an object. The operations are defined using functions. The functions for the objects are called methods in Python13.To find the id for an object, use the id(object) function. To find the type for an object, usethe type(object) function.14.(b)15.s.lower() is "\tgeorgia\n"s.upper() is "\tGEORGIA\n"16.s.strip() is "Good\tMorning"17.The return returned from invoking the format function is a string.18.The width is automatically increased to accommodate the size of the actual value.19.57.46812345678.957.4057.4020.5.747e+011.2e+075.74e+015.74e+0121.5789.4685789.4685789.405789.405789.4022.45.747%45.747%23.45452d2d24.Programming is funProgramming is funProgramming is fun25.turtle.home()26.turtle.dot(3, "red")27.Draw a square28.turtle.speed(number) # Set a number between 1 to 10, the larger, the faster29.turtle.undo()30.turtle.color("red")31.turtle.begin_fill()turtle.color("red")turtle.circle(40, steps = 3) # Draw a triangle ...turtle.end_fill()32.turtle.hide()。
python核心编程第5章课后练习题

python核⼼编程第5章课后练习题5-2. 操作符(a)写⼀个函数,计算并返回两个数的乘积(b)写⼀段代码调⽤这个函数,并显⽰它的结果def twoNumRide(a, b):'计算并返回两个数的乘积'c = a * breturn cif __name__ == '__main__':cj = twoNumRide(2, 3)print(cj)----------------------------------------------------------------------------------------------------------------5-3. 标准类型操作符,写⼀段脚本,输⼊⼀个测验成绩,根据下⾯标准,输出他们的评分成绩(A-F)A:90~100 B:80~89 C:70~79 D:60~69 F<60def queryScore(num):"""5-3. 标准类型操作符,写⼀段脚本,输⼊⼀个测验成绩,根据下⾯标准,输出他们的评分成绩(A-F)A:90~100 B:80~89 C:70~79 D:60~69 F<60:param num::return:"""if 90<= num <= 100:print('A')elif 80<= num <=89:print('B')elif 70<= num <=79:print('C')elif 60<= num <=69:print('D')else:print('F')if __name__ == '__main__':score = input('请输⼊0~100的分数:')queryScore(int(score))--------------------------------------------------------------------------------------5-4 取余。
python核心编程第二版课后题答案第五章

def ji(x1, x2):'''5-2 返回两个数的乘积'''return x1*x2def grade(score):'''5-3 输入乘积0~100份之内,返回评分'''if 90<=score<=100:return 'A'elif 80<=score<=89:return 'B'elif 70<=score<=79:return 'C'elif 60<=score<=69:return 'D'elif 60>score:return 'F'def isleapyear(year):'''5-4 输入年份,判断是否是闰年,年份小于172800年有效''' if (year%4==0 and year%100 !=0) or year%400==0: return Truereturn Falsedef minmoney(money):'''5-5 将任意一个美元(小于1美元)分成硬币由1美分,5美分,10美分,25美分且硬币数量是最少的一种组合方式'''m1 = int(money*100)m25 = m1/25m1 -= m25*25m10 = m1/10m1 -= m10*10m5 = m1/5m1 -= m5*5# 1美分,5美分,10美分,25美分return [m1,m5,m10,m25]def computer(cmd):'''5-6 输入类似x * y 这样的式子,自动获得值'''ops = ['+','-','**','/','%','*']for op in ops:if op in cmd:cmds = cmd.split(op)cmds[0]=float(cmds[0])cmds[1]=float(cmds[1])if op == '+':return sum(cmds)if op == '-':return cmds[0]-cmds[1]if op == '**':return pow(cmds[0],cmds[1])if op == '/':return cmds[0]/cmds[1]if op == '%':return cmds[0]%cmds[1]if op == '*':return cmds[0]*cmds[1]def tax(value, tax=0.17):'''5-7 输入价格,获得营业税,这里假设税金是20%''' import decimalvalue = decimal.Decimal(str(value))tax = decimal.Decimal(str(tax))return value*taxdef square(x,y=None):'''5-8(a)-1 求正方形或者长方形面积'''if y == None:y = xreturn x*ydef cube(x,y=None,h=None):'''5-8(a)-2 求立方体的体积'''if y==None:y=xif h==None:h=xreturn x*y*hdef circle(r):'''5-8(b)-1 求圆的面积'''import mathreturn 2*math.pi*rdef sphere(r):'''5-8(b)-2 求球的体积'''import mathreturn 4./3*math.pi*r**3def f2c(f):'''5-10 华氏度转摄氏度FahrenheitDegree to CelsiusDegree''' return (f-32)*(5./9)def even(l):'''5-11(a) 求列表中数字的偶数'''rl = []for i in l:if i%2==0:if i in rl:continuerl.append(i)return sorted(rl)def odd(l):'''5-11(b) 求列表中数字的奇数'''rl = []for i in l:if i%2 != 0:if i in rl:continuerl.append(i)return sorted(rl)def individe(x,y):'''5-11(d) 是否能整除'''if x%y==0:return Truereturn Falsedef numinfo():'''5-12 输出当前系统关于数字的范围'''import sysl = {}maxint = sys.maxintminint = -maxintmaxlong = sys.maxsizeminlong = -maxlongmaxfloat = sys.float_info.maxminfloat = sys.float_info.minl['maxint'],l['minint'],l['maxlong'],l['minlong'],l['maxfloat'],l['minfloat'] = \ maxint,minint,maxlong,minlong,maxfloat,minfloatreturn ldef time2minute(time):'''5-13 将由小时和分钟表示的时间转换成只有分钟的时间'''times = time.split(':')return int(times[0])*60+int(times[1])def banktax(interest):'''5-14 返回年回报率'''import decimalreturn (decimal.Decimal(1)+decimal.Decimal(str(interest)))**365def gcd(num1,num2):'''5-15-1 最大公约数'''mins = num1cd = Noneif num2 < num1:num1,num2 = num2,num1cds = []for i in range(1, num1+1):if num1%i == 0:cds.append(i)cdslen = len(cds)for i in range(0,cdslen):if num2%cds[(cdslen-i-1)]==0:cd = cds[(cdslen-i-1)]breakreturn cddef lcm(num1,num2):'''5-15-2 最小公倍数'''# 需要gcd 函数cd = gcd(num1,num2)a = num1/cdb = num2/cdreturn cd*a*bdef payment(startmoney,monthout):'''5-16 给定初始金额和月开销数'''# 最大序号max = float(startmoney)/monthoutif not max.is_integer():max+=1max = int(max)# 格式化输出sapp = 3 - (len(str(startmoney)) - len(str(int(startmoney)))) # 3其实就是'.00' 的长度,sapp表示startmoney增加mapp = 3 - (len(str(monthout)) - len(str(int(monthout)))) # 后面其实是输入数据的数字长度减去他的整型部分slen = str(len(str(startmoney))+sapp) # startmoney 长度加上小数部分的补差长度mlen = str(len(str(monthout))+mapp) # monthout lengthstring = '%d\t$%'+mlen+'.2f\t$%'+slen+'.2f' # 输出格式L1, L2, L3 = len(str(max)), int(mlen)+1, int(slen)+1 # L1 L2 L3 第一第二第三栏宽度if L1 <5:L1 = 5print 'Amount Remaining'print 'Pymt#'.center(L1)+'\t'+'Paid'.center(L2)+'\t'+'Balance'.center(L3)print '-'*L1+'\t'+'-'*L2+'\t'+'-'*L3print string %(0,0,startmoney)for i in range(1,max+1):if startmoney>=monthout:startmoney-=monthoutelse:monthout = startmoneystartmoney = 0print string %(i,monthout,startmoney)def randomlist():'''5-17 生成N个元素由随机数n组成的列表其中1<N<=100 0<=n<=231 -1并排序'''import randomN = [i for i in xrange(2,101)]n = [i for i in xrange(-1,232)]Nn = random.choice(N)Return = []for i in xrange(0,Nn):num = random.choice(n)n.remove(num) # 从n 列表中删除已经选过的数字Return.append(num)return sorted(Return)。
Python程序设计第五章知识点概要和任务单

字典变量名[键值]=赋给新值
4、字典元素的添加:
字典变量名[新增加的键值]=新键值对应的内容
或者 字典变量名.update({新增键值1:新键值1对应内容1,...,新增键值n:新键值n对应内容})
5、字典元素的删除:
del字典变量名[要删除的键值]
6、字典元素的遍历:
具体任务:
例1:正确的字典定义:d={1:100,2:200,3:300}或者d={"a":100,(1,):200,[3]:300}
例2:错误的字典定义:d={"a":100,(1,):200,[3]:300}(因为选择列表[3]作为键值,故出错)
例3:字典中元素的访问
>>> d={0:"sprint",1:"summer",2:"autumn",3:"winter"}
二、分节知识点概述及任务要求:
5.1python中字典数据类型。
知识点概要:
1、字典的定义:
字典变量名={键值1:键值1对应的内容,......键值n:键值n对应的内容}
注意:键值一定是不可变的量,如数字,字符串,或元组等,像列表这样的可变量当不了键值。
2、字典中元素的访问:
字典变量名[键值]或者字典变量名.get(键值)
>>> d(显示新增元素后字典d的内容)
{0: 'sprint', 1: 'summer', 2: 'autumn', 3: 'winter', 4: 'qtw'}
例2:
{0: 'sprint', 1: 'summer', 2: 'autumn', 3: 'winter', 4: 'qtw'}
Python语言程序设计习题与答案

一、单选题1、字符串是一个字符序列,例如,字符串s,从右侧向左第3个字符用什么索引?A.s[3]B.s[-3]C.s[0:-3]D.s[:-3]正确答案:B2、获得字符串s长度的方法是什么?A.s.len()B.s.lengthC.len(s)D.length(s)正确答案:C3、字符串函数strip()的作用是什么?A.按照指定字符分割字符串为数组B.连接两个字符串序列C.去掉字符串两侧空格或指定字符D.替换字符串中特定字符正确答案:C4、"abc"的长度是3,"老师好"的长度是多少?A.1B.3C.6D.9正确答案:B5、字符串是一个连续的字符序列,用什么方式打印出可以换行的字符串?A.使用转义符\\B.使用\nC.使用空格D.使用“\换行”正确答案:B6、Python中布尔变量的值为A.0,1B.真,假C.T,FD.True,False正确答案:D7、Python通过什么来判断操做是否在分支结构中A.缩进B.冒号C.花括号D.括号正确答案:A8、对负数取平方根,即使用函数math.sqrt(x),其中x为负数,将产生A.虚数B.程序崩溃C.什么都不产生D.ValueError错误正确答案:D9、以下的布尔代数运算错误的是A.not (a and b) == not (a) and not (b)B.(True or False) == TrueC.(True or x) == TrueD.(False and x) == False正确答案:A10、以下不可能出现在or操作真值表中的是A.F or T = TB.T or T = TC.F or F = TD.T or F = T正确答案:C11、Python语言中,与函数使用相关的保留字是哪个?A.passB.forC.evalD.def正确答案:D12、以下哪个不是函数的作用?A.降低编程复杂度B.复用代码C.增强代码可读性D.提高代码执行速度正确答案:D13、假设函数中不包含global保留字,下面对于改变参数值的说法,哪个是不正确的?A.参数的值是否被改变,与函数中对变量的操作有关,与参数类型无关。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Chapter 5 Loops
1. count < 100 is always True at Point A. count < 100 is
always False at Point C. count < 100 is sometimes True or
sometimes False at Point B.
2.
It would be wrong if it is initialized to a value between 0 and 100, because it could be the number you attempt to guess.
When the initial guess value and random number are equal, the loop will never be executed.
3. (a) Infinite number of times.
(b) Infinite number of times.
(c) The loop body is executed nine times. The printout is 2, 4, 6, 8 on
separate lines.
4. (a) and (b) are infinite loops, (c) has an indentation error.
5.
max is 5
number 0
6.
sum is 14
count is 4
7.
Yes. The advantages of for loops are simplicity and readability. Compilers can
produce more efficient code for the for loop than for the corresponding while
loop.
8. while loop:
sum = 0
i= 0
while i <= 1000:
sum += i
i += 1
9. Can you always convert a while loop into a for loop?
Not in Python. For example, you cannot convert the while loop in Listing 5.3,
GuessNumber.py, to a for loop.
sum = 0
for i in range(1, 10000):
if sum < 10000:
sum = sum + i
10.
(A)
n times
(B)
n times
(C)
n-5 times
(D)
The ceiling of (n-5)/3 times
11.
Tip for tracing programs:
Draw a table to see how variables change in the program. Consider (a) for example.
i j output
1 0 0
1 1
2 0 0
2 1 1
2 2
3 0 0
3 1 1
3 2 2
3 3
4 0 0
4 1 1
4 2 2
4 3 3
4 4
(A).
0 0 1 0 1 2 0 1 2 3
(B).
****
****
2 ****
3 2 ****
4 3 2 ****
(C).
1xxx2xxx4xxx8xxx16xxx
1xxx2xxx4xxx8xxx
1xxx2xxx4xxx
1xxx2xxx
1xxx
(D).
1G
1G3G
1G3G5G
1G3G5G7G
1G3G5G7G9G
12.No. Try n1 = 3 and n2 =3.
13. The keyword break is used to exit the current loop. The program in (A) will
terminate. The output is Balance is 1.
The keyword continue causes the rest of the loop body to be skipped for the current iteration. The while loop will not terminate in (B).
14. If a continue statement is executed inside a for loop, the rest of the iteration is skipped, then the action-after-each-iteration is performed and the loop-continuation-condition is checked. If a continue statement is executed inside a while loop, the rest of the iteration is skipped, then the loop-continuation-condition is checked.
Here is the fix:
i = 0
while i < 4:
if i % 3 == 0:
i += 1
continue
sum += i
i += 1
15.
TestBreak.py
sum = 0
number = 0
while number < 20 and sum < 100:
number += 1
sum += number
print("The number is " + str(number))
print("The sum is " + str(sum))
TestContinue.py
sum = 0
number = 0
while (number < 20):
number += 1
if (number != 10 and number != 11): sum += number
print("The sum is " + str(sum))
16.
(A)
print(j)
1
2
1
2
2
3
(B)
for j in range (1,4):
1
2
1
2
2
3。