同济《Python程序设计》课后习题参考答案.docx

上传人:太** 文档编号:46647715 上传时间:2022-09-27 格式:DOCX 页数:11 大小:27.73KB
返回 下载 相关 举报
同济《Python程序设计》课后习题参考答案.docx_第1页
第1页 / 共11页
同济《Python程序设计》课后习题参考答案.docx_第2页
第2页 / 共11页
点击查看更多>>
资源描述

《同济《Python程序设计》课后习题参考答案.docx》由会员分享,可在线阅读,更多相关《同济《Python程序设计》课后习题参考答案.docx(11页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。

1、一、选择题LB 2.D3.C4.C二、简答题(1)简单易学(2)解释性(3)可移植性(4)可扩展性(5)面向对象(6)丰富的库Web应用开发(2)自动化运维.网络安全(4).网络爬虫(5).游戏开发(6).数据分析.人工智能三、编程题l.print(Helio, World!.)2*)printCttHelIo Python World!)print,*)第2章2.6习题一、选择题I.C 2.D3.C4.A5.B6.D二、填空题2.26 2.type() 3.274. -5.75; -65. False三、简答题1 .(1)变量名必须由字母、数字、或者下划线(_)组成。(2)不能使用空格、连字

2、符、标点符号、引号等其他特殊字符。(3)以字母或下划线开头,但不能以数字开头(4)严格区分大小写。(5)要避免与Python关键字和函数名冲突.见表2.4.第3章3.4综合实验#1si = keep on going never give up 52 = si.capital ize()print(s2)#253 = s2.strip()print(s3)#3print (s3.endswith(up)#4print (sS.startswithCon*)import mathsidejength = int(input(请输入正方形的边长:)def equal_radius():print(

3、niath.sqrl(pow(side_lenglh,2)/ina(h.pi)cqual_radius()一、选择题LA 2.A3.D4.A5.B二、简答题类变量指的是定义在类中,但在各个类方法外的变量。类变量的特点是:所有类的实例化 对象都可以共享类变量的值,即类变量可以在所有实例化对象中作为公用资源。实例变量 指的是定义在类的方法中的属性,它的特点是:只作用于调用方法的对象。需要注意的是, 实例变量只能通过对象名访问,无法通过类名直接访问。Pyihon允许通过对象访问类变量, 但无法通过对象修改类变量的值。因为,通过对象修改类变量的值,不是在给“类变量赋 值”,而是定义新的实例变量。继承:

4、实现代码的重用,不需要重发编写代码。子类拥有父类所有的属性和方法。也可以 重新父类方法。封装:根据职责将属性和方法封装到一个抽象的类中。多态:不同的对象 调用相同的代码,产生不同的效果,提高代码的灵活性。三、编程题1:class StudcntO:def_init_(self,name,num,gender): self._name = name self.num = num self.gender = genderdef setName(self, name): self._name = namedef gctNamc(sclf):return self._namedef setGender

5、(self, gender): self.gender = genderdef getGender(self): return self._gender2:class Animal():def show(self):prim (动物的特性”)class Dog(Animal):definit_(self,ability):sclf.abilityl = abilitydef show(self):prim(小狗会 s”(self.ability I)class Bird(Animal):def_init_(self,ability):self.ability2 = abilitydef sho

6、w(self):prini(“小鸟会 s”(self.abilily2)def func(tcnip):temp.show()dog = Dog(跳)bird = Bird(飞)func(dog)func(bird)第9章一、选择题l.B 2.A3.A4.D5.C二、简答题绝对路径:指的是从盘符开始的路径,通常要比相对路径要长。相对路径:指的是从当前路径开始的路径。1. pickle模块可以用来处理所有Python的数据类型,而json模块只能用来处理基本数 据类型。(2)pickle模块在序列化后的数据类型变为二进制类型,在进行读写式需要采用*b模式, 而json模块在序列化后的数据类型变为

7、json串(字符串)类型。(3)pickle模块主要用于Python程序对象的持久化和程序之间的对象网络传输,而json 可用于各种语言之间的字符转换。三、编程题(1)file_pa(h = D:cgjWowel.txtwith open(file_path,w) as file:print(情依次输入A,E,LO,U五个元音字母)for i in range(5):passage = inpul(请输入大写的元音字母:) file.write(passage + n)(2) file_path = D:cgjVowel.txtwith opcn(filc_path,r) as file:co

8、ntents = flle.readlines();with openCDAcgjWowe.txt/w) as :for num in contents:s = nuin.lover()file_l.write(s)1. (1)num = 10students = name_list =j= 1for i in range(num):name = input(please input student name:)if name not in name_list:name_list.append(name)else:name = name + slr(j)j+= 1namejist.append

9、(name)gender = input(please input + name + *s gender :) class_namc = input(plcasc input + name + s class_namc:) grade = inpul(please input + name + s grade:) studentsfname = gender,class_name,gradeprint(students)(2) num = 10students = namc_list = |j= 1for i in range(nuni):name = input(please input s

10、tudent name:)if name not in name_list:namejist.appcnd(namc)else:name = name + str(j)j += name_list.append(name)gender = input(please input + name + s gender :) class_name = input(please input + name + s class_name:) grade = inpuUplease input + name + ”s grade:) studentsname = gender,class_nanie,grad

11、efile_path = D:cgjsludents.txtwith opcn(file_path,w) as file:for key,value in students.i(ems():file.write(key + + str( value) + *n)(3) import picklenum = 10students = namc_list =j= 1for i in range(num):name = input(please input student name:)if name not in name_list:naine_iist.append(name)else:name

12、= name + str(j)j += nanic_list.appcnd(name)gender = input(please inpul + name + s gender :) class_name = input(please input + name + s class_name:) grade = input(please input + name + s grade:)studentsfnamel = gender.class_name,gradeprint(studcnts)file_path = D:cgjstudents2.txtwith open(file_path,wb

13、) as file:for key.value in students.items():picklc.dump(key,file)pickle.dunip(str( value),file)第10章一、选择题l.C 2.B二、填空题1. shape、size 2. Series DataFrame 3.scatter pie bar 二、编程题.1. import numpy as npimport niatplotlib.pyplot as pitx = np.arange(0, 2 *np.pi, 0.1)y = np.sin(x)plt.figure()plt.xlabel(x)plt.

14、ylahcl(y)plt.plot(x, y,color=b)import numpy as npimport niatplotlib.pyplot as pitimport mpl_toolki(s.mplot3dx,y = np.mgrid-2 : 2 : 20j, -2:2: 20jz = 50 * np.cos(x + y)ax = plt.subplot( 111. projection = 3d)ax.plot_surface(x, y, z, rstride = 2, cstridc = 1, cmap = plt.cm.Blucs_r)ax.set_xlabel(,X)ax.s

15、et_ylabel(Y)ax.set_zlabel(Z)#5 print (s3.replace(e,aa) #6print (sS.splitCn1) #7print (s3.upper()#8nl = Lilyprint (%s says: %s.%(nl,s3) #9print (s3.center(40,#)#10print (s3.count(e) #11print (s3.split() #12print (7,.join(s4) #13print ( .join(s4:-l)1. 5习题一、选择题 l.B 2.D3.C4.C二、填空题 1. moonshipfricnd 3.54

16、. bEIjlNGspam 三、编程题 1.strl = I want lo go to Beijing. Berli and Beijing this year. How about you? str2 = strl.split() str2 = .join(str2) print (str2) 2. 思路:(1) .变量名的第一个字符是否为字母或下划线(2) .如果是,继续判断-4(3) .如果不是,报错(4) .依次判断除了第一个字符之外的其他字符.判断是否为字母数字或者下划线 while True:s = inputf请输入字符(q退出):)if s = q: exit()#判断字符串

17、第一个变量是否满足条件if sfOl.isalphaO or sfO =for i in sl:#判断判断除了第一个元素之外的其他元素是否满足条件if i.isalnum() or i =continueelse:prim(不合法)breakelse:print。合法)else:printC不合法)3.#!/usr/bin/env python#coding:utf-8s = input(输入:)si = s.split()s2 = sl0.uppcr()s3 = sl-ll.upper()print (s2.count(s3)4.s = input(inpul a string:n) let

18、ters, space, digit, others = 0,0,0,0 fbr c in s:if c.isalpha():letters += 1elif c.isspace():space += Ielif c.isdigitO:digit += 1else:others += 1print (char = %d,space = %d,digit = %d,o(hers = %d % (letters,space,digit,others)第4章4.4 综合实验#01fav_city =#02fav_city.append(Qinghai)fav_city.append(Chengdu)

19、favity.appendCDalian)fav_city.append(Xizang)fav_city.appcnd(Hacrbin)print (fav_city)#03fav_city0 = Qingdao#04fav_city.inserl(2,Kunming)#05del fav_city0#06fav_city.rcniovc(Xizang)#07fav_city.sort()#08fav_city. re verse()#09for city 1 in fav_city:print (cityl)#10tuplc_city = tuplc(fav_city)#11len(tupl

20、e_city)4.5 习题一、选择题1. D 2.A3.B4.D5.C二、填空题1.(123,22, 123,222. x = 1,3,5,7,93. 11,22,33,114. Flase5. b= :26. (6,)三、编程题#1import randomx = random.randint(0,100) for i in range(10)J x.sort()print (x)#2.listl = Hollywood, Mexico, *New Delhi, Tokyo item = listl.pop(O)listl.append(item)print (lisll)#3a = int

21、(input(a:)for b in x:if a b:x.insert(x.index(b),a)breakelse:x.append(a)print (x)#3x.pop()x:5 = sorted(x:5 reverse = True)x5: = sorted(x5:)print (x)4.#列表推导法listl = 22,11,33,22,44,33tcn】pist=| for x in listl:if x not in tcmp_list:temp_list.append(x)print (tcnip_list) #输出结果未排序#排序方法listl =22,11,33,22,44

22、,33list2 = sorted(listl)tempist =i = 0while i Ien(list2):if Iist21i| not in temp_list:temp_list.append(list2i)else:i+= 1print (tcmp_list) #输出结果己排序第5章字典综合实验1.Qing_Hai = qinghai/xining, W,8,18100001Si_Chuan = sichuan,chengdu1, J11*,21 ,610(X)OJGan_Su =gansiTJanzhou,陇,14330000Ning_Xia = l,ningxia,yinch

23、uan,;T,5:750()(M),JNei_MengGu =neimenggu?huhehao(e,内蒙古:1210l00()。,Shaan.Xi =shaanxi,xian?陕,10310000Shan_Xi = shanxi/taiyuan:, 11 :030000He_Nan =hcnan;zhengzhou;像,18,4500001Shan.Dong = shandong,jinan;f-, 16:250000provinces=lQing_Hai,Si_Chuan,Gan_Su,Ning_Xia,Nci_McngGu,Shaan_Xi,Shan_Xi,Hc_Nan,Shan_Don

24、g Yellow_River_basin = for province in provinces:Yellow_River_basinprovinceOJ = province! I: print(Yellow_River_basin) 2.#遍历嵌套字典的键for key in Ycllow_Rivcr_basin.kcys(): print(key)#遍历嵌套字典的值fbr value in Yellow_River_basin.values(): print( value)#遍历嵌套字典的键值对for key, value in Yellow_River_basin.items(): p

25、rint(kcy+s Capital is : %s ,%valuc0+H For_short is : %s%value 1 +Area_manage is : %d 个 %value2+Postal_code is : %s%value3) 3.for provinc in Yellow_River_basin.keys():if provinc = sichuan:Yellow_River_basinprovincl =chengdu丁蜀21, 6IOOOOl elif provinc = gansu:Yellow_River_basin|provinc = lanzhou1,14, 7

26、30000elif provinc = shaanxi:Ycllow_Rivcr_basin| provinc 1 =秦 print(Yellow_River_basin) 4qinghai = name:QingHai,capiial:XiNing,for_short:青,area_manage:8 sichuang = nameTSiChuan,capital:ChengDu,fbr_short:川?area_manage:21 gansu = name:GanSu,capital:LanZhou,for_short:陇,area_manage: 14 ningxia = name:Nin

27、gXia,capital:YinChuan,for_short:宇,area_manage:5 neimenggu = namc:Neimenggu,capital:HuhcHaote,for_short:内 蒙 A ,arca_manage: 12 shaanxi= nameTShaanXLcapital:XiAn?for_short:陕,area_manage:10 shanxi = naincYShanXicapitalfTai YuanVfor.shonf/area-manage: 11 henan = nameYHeNan/capitarfZhengZhou/foshortrft/a

28、rea.manage: 18 shandong = hame:ShanDong?capital:JiNan?for_short:鲁,areaTianage: 16 basinjist = qinghai,sichuang,gansu,ningxia,ncimcnggu,shaanxi,shanxi,henan,shandong Postal_Code=,810000;610000,730000,750000,010000,710000,030000:450000,250000 prin【(basinisl) 5for province_num in range(len(basin_list):

29、basinistprovinceiumpostal_code = Postal_Codeprovince_numprint(basinist)第5章综合实验一、选择题LB 2.C3.B4.D5.D二、简答题1. (1)字典的键(key)具有唯一性。(2)字典的键(key)是不可变的。2. 依据:(1)当需要存取的数据是同一种类型时可以使用列表。(2)当需要存取的数据不是同一种类型时可以使用字典。解决问题:对多个事物进行添加、删除和修改,同时对这些事物多个键(key)映射相对应多 个值(value)进行添加、删除和修改的问题。三、编程题(1) vowels = LA/E/I/O/UJvowels

30、_dict = for letter in vowels:vowels_dict letter = ord(Ietter)print(vowcls_dict)(2) for key, value in vowels_dict.items():vowels_dictlkeyj = chr(value+32)print(vowels_dict)1.Capital = ChinafBcijingVGcnnanyBcrlinVBrazirfRio DE JaneiroCapital_str = str(Capiial)Capital_list =for i in Capital:Capital_lis

31、t.append(i)print(Capital_list)(1) C叩 ital_strist =for j in Capital_str:Capital_str_list.append(j)print(Capital_str_list)一、选择题l.D 2.B3.C4.A5.C二、简答题注意事项:(1)if语句的判断语句后的冒号(:)是必须要有的,如果冒号缺失将会出现SyntaxError 的报错。(2) python语言利用缩进量的一致性来确认判断语句是否属于同一个语句块。配对原则:if和else的配对关系,else总是和距离它距离最近的未配对的if进行匹配。1.(1) break语句的

32、作用是立即退出循环,在退出循环之后不再运行循环中剩余的代码,也 不再判断循环条件是否成立。break语句可以使程序从循环体内跳出循环体,即让循环提 前结束,接着执行循环之后的语句。(2) continue语句的作用是结束正在执行的本次循环,即跳过循环体内尚未被执行到的语 句块,然后返1口1到循环的开头执行下一次的循环,判断执行循环的条件是否成立。若判断 成立则继续执行循环,否则将会结束运行。三、编程题(1)letter = input(请任意键入5个英文大小写字符(至少有一个大写字母):)for a in letter:if a.isupper():break;else:print(a)(2)

33、letter = input(请任意键入5个英文大小写字符(至少有一个大写字母):)for a in letter:if a.isupper():continue;piint(a);def prinl_number():number = input(请任意键入一个数字:)number = int(number)if(numbcr-5):print(2*number+l)elif(-5=number & number=5):print(2*number)else:print(2*numbcr-l)print_number()一、选择题l.D 2.C二、简答题l.D 2.C二、简答题3.A4.C5

34、.A形参:函数定义时使用的参数叫做函数的形参(形式参数实参:函数调用时传递的参数叫做实参(实际参数)。联系:函数在调用时是将实参的引用(内存中的地址)传递给形参,系统会根据实参的值 自动判定形参的类型。绝对路径:指的是从盘符开始的路径,通常要比相对路径要长。相对路径:指的是从当前路径开始的路径。1. (1)import模块名称(2) from模块名称import导入对象名称from 模块名称 import *(3) import模块名称as模块简写三、编程题l.def generate( number):fbr i in range(l.number):r.appcnd(list(map(la

35、inbda x,y:x+y, |0+r-1,r-l+()return r:numbera=gcncrate( 10)for i in a:print(i)2. (1)import mathsidejength = inl(inpul(请输入正方形的边长:)radius = int(input(请输入圆的半径:)zhouchang = lambda x:4*xarea = lambda x:x*x*math.piprint(zhouchang(side_length)print(area(radius)(2)import mathsidejength = int(input(请输入正方形的边长:)radius = int(input(请输入圆的半径:)defzhouchangO:print(4*side_length)def area():print(pow(radius,2)*math.pi)prinl(正方形的周长为:)zhouchangOprint(”圆的面积为:”)area()(3)

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 应用文书 > 解决方案

本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知淘文阁网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

工信部备案号:黑ICP备15003705号© 2020-2023 www.taowenge.com 淘文阁