收藏 分销(赏)

Python程序设计基础课后练习题答案1-13章全.docx

上传人:快乐****生活 文档编号:3157992 上传时间:2024-06-21 格式:DOCX 页数:34 大小:44.71KB
下载 相关 举报
Python程序设计基础课后练习题答案1-13章全.docx_第1页
第1页 / 共34页
Python程序设计基础课后练习题答案1-13章全.docx_第2页
第2页 / 共34页
点击查看更多>>
资源描述
第一章 判断题:1-4:√ × √ √ 第二章 判断题:1-5:√ × × √ √ 6-10:× × √ √ √ 11-15:× √ √ × √ 添加代码题: 1.我们都知道,下面的代码: print “I like writing in Python.” print “It is so much fun.” 执行后,运行结果为: I like writing in Python. It is so much fun. 你能只用一行代码实现上述效果吗? 第3章 习题参考答案: 一、 选择题 ABABB 二、 简答题 1.break或continue语句用来提前跳出循环,即循环条件没有满足False时或者序列还没被完全递归完,也会停止执行循环语句。其中,continue 语句用于跳出本次循环,而break用于跳出整个循环。 该程序段的功能是检查用户输入的用户名及密码是否正确,输入正确则显示“登录成功”;输入错误则由用户重新输入,但输入错误次数超过3次则不允许再次输入,直接显示“登录失败”。 break在此程序段中的作用是当输入用户名和密码正确时或输入错误次数超过3次时直接结束循环。 2.Python语句代码缩进的书写原则:在逻辑行首的空白(空格和制表符)用来决定逻辑行的缩进层次,从而用来决定语句的分组。这意味着同一层次的语句必须有相同的缩进。有相同的缩进的代码表示这些代码属于同一代码块。 代码段1和代码段2的区别在于“print(sum)”这个语句的位置。在代码段1中,“print(sum)”和“for i in range(10):”在同一层次,表示它们是并列的语句,“print(sum)”不在循环体内,所以循环结束后才输出sum的值;而在代码段2中,“print(sum)”在循环体内,表示每循环一次都会输出一次sum的值。 3.错误1:循环嵌套代码的缩进 错误2:range(1,4)只是包括1,2,3,不包括4。所以要改成range(1,5) 错误3:if( i!=j!=k)的写法不对。改为if( i!=j and j!=k) 4.输出结果 >>> 1 3 5 5. bonus1 = 100000 * 0.1 bonus2 = bonus1 + 100000 * 0.500075 bonus4 = bonus2 + 200000 * 0.5 bonus6 = bonus4 + 200000 * 0.3 bonus10 = bonus6 + 400000 * 0.15 i = int(raw_input('input gain:\n')) if i <= 100000: bonus = i * 0.1 elif i <= 200000: bonus = bonus1 + (i - 100000) * 0.075 elif i <= 400000: bonus = bonus2 + (i - 200000) * 0.05 elif i <= 600000: bonus = bonus4 + (i - 400000) * 0.03 elif i <= 1000000: bonus = bonus6 + (i - 600000) * 0.015 else: bonus = bonus10 + (i - 1000000) * 0.01 print 'bonus = ',bonus 6. if score>=90: print("A") else: 60<=score<90: print("B") else: print("C") 7. str=input("enter a sentence:") for char in str: if 65<=ord(char)<=90 or 97<=ord(char)<=122: print("英文字母") elif ord(char)==32: print("空格") elif 48<=ord(char)<=57: print("数字") else: print("其它字符") 8. num1=1 num2=2 sum=0 for i in range(1,21): sum=num2/num1 num2=num1+num2 num1=num2 print(sum) 9. num=int(input("enter a num:")) i=0 while num>0: print(num%10,end='') i+=1 num=num//10 print("\n这个数是%d位数"%i) 10. for i in range(100,1000): if i %7==0 and i//10%10==2: print (i) 11. j=0 for i in range(2000,2501): if i %400==0 or i%4==0 and i%100!=0: j+=1 print(i,end=" ") if j %8==0: print("") 12. i=7 while True: if i%2==1 and i%3==2 and i%4==3 and i%5==4 and i%6==5 and i%7==0: print(i) break i+=1 13. total=13 i=0 while total<=26: total=total*(1+0.008) i+=1 print(i) 14. num=int(input("please enter num:")) flag=True for i=2 to num-1: if num%i==0: flag=False if flag: print("%d是素数"%num) else: print("%d不是素数"%num) 15. k=0 for i in range(1,1001): flag=True for j in range(2,i): if i%j==0: flag=False if flag: k+=1 print(i,end=' ') if k%10==0: print("") k=1 16. a=int(input("enter a:")) b=int(input("enter b:")) c=int(input("enter c:")) if a<b: a,b=b,a if a>c: if b>c: print(a,b,c) else: print(a,c,b) else: print(c,a,b) 三、 实训题 1. 求最大公约数代码参考书上例3.6。求出最大公约数后即可相应求出最小公倍数。 2. 求1!+2!+3!+…+20! 参考代码: sum=0 for i in range(1,21): t=1 for j in range(1,i+1): t*=j sum+=t print(sum) 3. 输出斐波那契数列的前20项 参考代码: f1=1 f2=1 for i in range(1,21): print(f1,f2) f1+=f2 f2+=f1 4. 编程找出1000之内的所有完数,并输出其因子。 参考代码: l = [ ] for n in range (1,1001): for a in range (1,n): if n%a ==0: l.append(a) if sum(l)==n: print (l) print (n) l = [] 5. 输出九九乘法表 参考代码: for x in range(1,10): for y in range(1,x+1): r=x*y print ('%d * %d = %-2d' %(y,x,r),' ',end='')#%d格式化成整数,- 代表左对齐,数字代表占位。 print (end='\n')#这一句代表,每次遍历完一个周期换行,并下一次遍历的结果将从该行输出。如果是print()将从下一行开始输出。 6. 输入一系列数字,并求和与求平均数。 sum=0.0 i=0 num=int(input("请输入数字,以0结束")) while num!=0: sum+=num num=int(input("请输入数字,以0结束")) i+=1 average=sum/i print("加起来总数为%d,平均数%f"%(sum,average)) 第4章课后练习答案: 一、填空题: 1.'h/e/l/l/o/ /w/o/r/l/d/!' 2.回车换行 3.False 4.(1) str[-1::-1] (2) str.upper() (3)str[5:12] (4)str[::2] (5) '/'.join(list(str)) (6)'www.sina.www.gdpu.www.good.www.tianya'.replace('www','万维网') 5.'c:\\test.htm' 6. 1 7. 'HELLO WORLD' 8. True 9. '123456' 10.True 二、简答题: 1. 假设有一段英文,其中有单词中间的字母“i”误写为“l”,请编写程序进行纠正。 x = "i am a teacher,i am man, and i am 38 years old.I am not a businessman." x = x.replace('i ','I ') print(x) 2. 有一段英文文本,其中有单词连续重复了2次,编写程序检查重复的单词并只保留一个。例如文本内容为“This is is a desk.”,程序输出为“This is a desk.” x='This is a a desk.' pattern=pile(r'(?P<f>\b\w+\b)\s(?P=f)') matchResult=pattern.search(x) x=x.replace(matchResult.group(0),matchResult.group(1)) print(x) 3. 编写程序,用户输入一段英文,然后输出这段英文中所有长度为3个字母的单词。 import re words=input("Input the words:") l=re.split('[\. ]+',words) #使用空格分隔词语,得到各个单词 print(l) i=0 #这里我设置的是计数器 for i in l: if len(i)==3: #如果单词的长度为3 输出 print(i) else: print('') 4. 求s=a+aa+aaa+aaaa+aa...a的值,其中a是一个数字。例如2+22+222+2222+22222(此时共有5个数相加),几个数相加由键盘控制。 num=int(input("请输入一个数字")) count=int(input("请输入数字的位数")) sum=0 temp=0 for i in range(count): temp+=num*10**i print(temp) sum+=temp print(sum) 5. 一个数如果恰好等于它的因子之和,这个数就称为完数。例如6=1+2+3。编程找出1000以内的所有完数。 #encoding:utf n=input("Please input a number!") sum=0 printS="" for i in range(1,n): if n % i==0: sum=sum+i if sum>n: print "%d is 不足数"%n elif sum<n: print "%d is 丰沛数"%n else: print "%d is 完数"%n printS= str(n) + " = " for i in range(1,n): if n% i==0: printS+= str(i) + "+" print printS[0:len(printS)-1] 6. 打印出如下图案。 (1) for i in range(1,10): print(' '*(10-i),end='') print(str(i)*(2*i-1)) (2) n="123456789" for i in n[-1:0:-1]: s=n[-1:int(i)-2:-1] print ("%s*%d+%d=%d"%(s,9,int(i)-2,int(s)*9+int(i)-2)) 实战作业 1、输入一串字符串,判断它是不是回文数。如Madam,I’mAdam是回文数。    提示:要把一串字符中所有的标点符号去除,并把所有的大写字符变成小写字符再进行比较。如“Madam,I’mAdam“,转化后变成“madamimadam”,正读与逆读是一样的,为回文。 import string #导入字符串函数库 string.punctuation='!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' string.whitespace='\t\n\x0b\x0c\r ' import string originalStr=raw_input("enter a string:") modifiedStr=originalStr.lower() badChars=string.whitespace+string.punctuation for char in modifiedStr: if char in badChars: modifiedStr=modifiedStr.replace(char,"") print "the originalStr is: %s\nthe modifiedStr is: %s\nthe reverseStr is: %s"%(originalStr,modifiedStr,modifiedStr[::-1]) if modifiedStr==modifiedStr[::-1]: print "字符串%s是回文"%originalStr else: print "字符串%s不是回文"%originalStr 2. 计算Poker中出现各种手数的概率,现给出Poker-hand-testing.data文件,其中有1000000条记录,要求读出每一条记录,并统计以下问题: 以下是每条记录的格式 : 3, 10, 1, 7, 2, 12, 4, 2 , 2, 1, 0 4, 9, 4, 12, 4, 13, 2, 6 , 3, 4, 0 3, 2, 2, 2, 3, 12, 3, 1 , 4, 2, 3 4, 11, 2, 8, 1, 13, 4, 7 , 1, 7, 1 4, 8, 3, 8, 1, 3, 1, 4 , 3, 7, 1 2, 7, 2, 5, 3, 10, 4, 13 , 3, 7, 1 1, 4, 3, 4, 3, 5, 4, 10 , 2, 10, 2 以下是各种类型的牌的编号: 图4-9 牌的类型 要求:(1)计算Poker有多少行; (2)计算包含1对牌的总手数与出现的概率; (3)计算所有牌类型出现的手数及概率 。 # count poker hands # 1. open the poker data file for reading poker_file = open("poker-hand-testing.data",'r') total_count_int = 0 # 2. create and initialize variable to hold the total count pair_count_int = 0 # create and initialize variable to hold pair count # 3. Loop through each line of the file for line_str in poker_file: total_count_int = total_count_int + 1 # (a). add one total for each hand fields = line_str.split(',') # (b). split on a comma hand_rank_str = fields[-1] # and get the last field hand_rank_int = int(hand_rank_str) if hand_rank_int == 1: #(c) if handRank is 1 (it is a pair) pair_count_int = pair_count_int + 1 # add one to pair count print("Total hands in file: ", total_count_int) # 4. print the values print("Count of pair hands: ", pair_count_int) print("Probability of a pair: {:>9.4%}".format(pair_count_int/total_count_int)) 3.智多星游戏: 计算机随机产生4种不相同的颜色序列,玩家不知道,让玩家输入四种颜色,与计算机随机产生的序列作比较,如果全部相同则显示猜对了,否则重新输入,设定总的输入次数,超过总次数,则失败。 要求如下:(1)设定总的尝试次数。 (2)如果输入的颜色与随机序列在位置与颜色都相符,则打印“★”。 (3)如果输入的颜色与随机序列的颜色相符,但是位置上不相符,则打印“☆”。 (4)如查输入的颜色与位置都不对,则打印“●”。 (5)当输入的颜色与位置都对了,就显示猜对了。 (6)如果超过总的输入次数,就显示失败。 #encoding:gbk import random import winsound i=0 s="RYBGCOPW" str="" j=0 corr="" #产生四个随机颜色与位置,并不能重复 while j<4: tempChar=random.choice(s)#生成一个随机字符 if tempChar not in str: str+=tempChar j+=1 #循环12次 while i<=12: print "This is the %dth try"%(i+1) inputColor=raw_input("Please enter 4 colors(\"RYBGCOPW\"):") if len(inputColor)!=4:#长度超过4个字符或者不够4个字符不予判断,请注意Continue的用法 print "WRONG ENTER! \nYou must enter 4 color(\"RYBGCOPW\")!" continue for k in range(0,4):#对每一种颜色进行判断 if inputColor[k]==str[k]: corr+="★" elif inputColor[k]!=str[k] and inputColor[k] in str: corr+="☆" else: corr+="●" print corr if corr=="★★★★": print "Bingo" winsound.Beep(400,2000) break else: corr="" i+=1 else: print"You Lost!" 第五章习题答案 一 选择题 1.C 2.B 3.C 4.B 5.C 6.B 7.A 二 简答题 1. 相对路径是相对于什么? 答:相对路径相对于当前工作目录 2. 绝对路径从什么开始? 答:绝对路径总是从根目录开始 3. os.getcwd()和os.chdir()分别是做什么? 答:os.getcwd()获得当前工作目录,os.chdir()改变工作目录。 4. 可以传递给open()函数的3种模式参数是什么? 答:r,表示以读的方式打开文件;w,表示以写的方式打开文件 ;a,表示以追加的方式打开文件。 5. read()和readlines()之间的区别是什么? 答:read()在未指定字符个数情况下会读取尽可能多的字符,有可能到文件末尾;readlines()则按行的方式读取文件,返回一个列表,每一行为列表中的一个元素。 三 编程题 1. import os os.mkdir("mydir") os.chdir("mydir") fi=open("mydoc.txt","w") while(1): str=input(); if str=="exit": break; fi.write(str) fi.close() 2. import os os.mkdir("mydir") os.chdir("mydir") f1=open("myfile.txt","w") str="I love programming with python" f1.write(str) f1.close() f2=open("myfileback.txt","w") f1=open("myfile.txt","r") str=f1.read() f2.write(str) f1.close() f2.close() 3. fileName=input("请输入文件名") f=open(fileName,"r") str=f.read() words=str.split() lines=str.split("\n") print("字符数: ",len(str)) print("单词数:",len(words)) print("行数: ",len(lines)) 4. fileName=input("请输入文件名") f=open(fileName,"r") str=f.read() scores=str.split() total=0 num=0 for s in scores: total+=float(s) num+=1 print("there are ",num,"scores") print("the total scores is:",total) print("the average score is:",total/num) 5. 电子表格操作 电子表单程序比如Microsoft Excel都有一个选项,可以将数据导出为CSV格式。在本练习中,创建程序,读取电子表格(CSV格式)并操纵它。程序应具有以下功能: (1) 显示数据 (2) 删除行或列 (3) 插入行或列 (4)更改指定单元格中的数据 (5) 输出CSV格式的数据 其中要考虑的问题有: 使用CSV模块,读取电子表格,选择恰当的数据结构来存储数据。该用列表、元组还是字典? 在程序中使用循环,提示输入上述操作的名字。接口方式是用单个字母来表示相关操作,例如“d”表格删除。 一、 填空题: 1. True 2.True 3.[6,7,9,11] 4.[5 for i in range(1,11)] 5.-1 6.[1, 4, 7] 7.[0, 1, 2, 3, 4] 8.del 9.False 10.14 11.[i for i in range(1,11)] 12. [i for i in range(1,11)][4:8] 13. L2[4]='bad';len(L2);L2.append('people');L2.sort();L2.pop() 二、简答题: 1.[i for i in range(1,21)] 2.[i for i in range(2,21,2)] 3.[chr(i) for i in range(65,91)] 4. list(str) 5. ''.join(strList) 6. '/'.join(list(str)) 7. 略。 8. mport random v=[random.randint(0,100) for i in range(20)] print(v) a=v[1:10] a.sort() b=v[11:20] b.sort() b.reverse() print(a) print(b) c=a+b print(c) 9. strList=[chr(i) for i in range(65,91)] strAll=[] for i in range(1,27): strAll.append(strList[:i:]) print (strAll) 10. 略 11. 首先sorted和sort 的区别主要在于sorted是将排序完的数据赋予给一个新变量,而sort则是在原变量的基础上直接进行排序,不产生新变量。 sorted是内建函数,而sorted是类函数,其使用必须跟在对象后面。 12. IP.split('.') 13. 略 14. 可以,可以 15. 列表是可以修改的,(2,3)为列表中的一个对象,可以被替换,但是它本身是不能修改的,如(2,3)改成(2,4)就不行。 元组是不能修改的,元组中的对象并没有被修改。只是元组中有个一个对象是列表,列表本身可以修改,但是对象没有变。 实战作业 1. 凯撒密码 (1) Text='ABCDEFGHIJKLMNOPQRSTUVWXYZ' Cipher='DEFGHIJKLMNOPQRSTUVWXYZABC' words=input("please input words:") str="" words=words.upper() for char in words: if char in Text: str+=Cipher[Text.index(char)] print str (2) Text='ABCDEFGHIJKLMNOPQRSTUVWXYZ' Cipher='DEFGHIJKLMNOPQRSTUVWXYZABC' words=input("please input words:") str="" words=words.upper() for char in words: if char in Cipher: str+=Text[Cipher.index(char)] print str 2. 编程实现《葛底斯堡演说》中单词的统计(gettysburg.txt)。 speach=[] unique=[] temp=[] count=0 file=open("gettysburg.txt","r") allwords=file.readlines() for words in allwords: temp=words.split() speach.extend(temp) print("总共有%d个单词"%len(speach)) for word in speach: if word not in unique: unique.append(word) print unique 一、选择题 1、C 2、B 3、C 二、问答题 1、字典是Python语言中唯一的映射类型。映射类型对象里哈希值(键,key)和指向的对象(值,value),通常被认为是可变的哈希表。字典对象是可变的,它是一个容器类型,能存储任意个数的Python对象,其中也可包括其他容器类型。 字典是Python中最强大的数据类型之一,它与列表、元组等其它序列类型的主要区别有以下几点: (1)存取和访问数据的方式不同 (2)映射类型中的数据是无序排列的。这和序列类型是不一样的,序列类型是以数值序排列的; (3)映射类型用键直接“映射”到值。 (4)字典支持索引操作(索引值为键值),但不支持切片操作,因为切片操作是针对索引值具有连续的,而字典的键不具备连续性。 (5)字典中的键必须是不可变且不重复,值可以是任何类型。 2、 (1)直接创建字典 创建一个空的字典 >>> mydict={ } #创建一个空的字典 >>> mydict #输出此字典的内容 {} (2) 通过dict函数创建字典 dict函数是字典类的构造函数,也可以利用此函数来创建字典。 创建一个空字典: >>> dict() {} 3、 (1)get函数:访问字典成员 get()函数根据key获取值。 >>> d={'one':1,'two':2,'three':3} >>> print(d.get('two')) (2)copy函数:返回一个具有相同键值的新字典 >>> x={'one':1,'two':2,'three':3,'test':['a','b','c']} #创建一个字典x >>> print(x) #输出字典x {'one': 1, 'two': 2, 'test': ['a', 'b', 'c'], 'three': 3} (3)pop函数:删除字典中对应的键 Pop函数可以删除字典中的键及其对应的值。 >>> d={'one':1,'two':2,'three':3} >>> d.pop('two') #删除键 'two' (4)fromkeys函数:用给定的键建立新的字典 fromkeys函数可以用给定的键建立新的字典,键默认对应的值为None >>> d=dict.fromkeys(['one','two','three']) (5)update函数:用一个字典更新另外一个字典 update函数可以用一个字典来更新另外一个字典。操作如下: >>> d={ 'one':123, 'two':2, 'three':3 } 实战作业: 1、 略(参考书中字典操作举例) 2、 def getdict(phone): A=[i for i in range(0,10)] B=["zero","one","two","three","four","five","six","seven","eight","nine"] mydict=dict(zip(A,B)) for i in phone: print mydict[int(i)] def main(): phone=raw_input("Please enter a series phone number:") getdict(phone) main() 3、 import string def Mostran(wholetext): f=open("e:\\Mos.txt","r") Mostext="" for line in f: Mostext+=line f.close() Lwhole=Mostext.split() L1=Lwhole[::2] #这种间隔分片出来就是列表 L2=Lwhole[1::2] MosDict=dict(zip(L1,L2)) for char in wholetext: print MosDict[char] def main(): temp=raw_input("Enter a passage:") temp=temp.upper() wholetext="" for char in temp: if char not in string.whitespace+string.punctuation: wholetext+=char translation=Mostran(wholetext) main() 第9章习题答案 一 选择题 1.B 2.C 3.B 4.D 二 简答题 1、什么是异常? 答:异常是一个事件,该事件会在程序执行过程中发生,影响了程序的正常执行。一般情况下,在Python无法正常处理程序时就
展开阅读全文

开通  VIP会员、SVIP会员  优惠大
下载10份以上建议开通VIP会员
下载20份以上建议开通SVIP会员


开通VIP      成为共赢上传
相似文档                                   自信AI助手自信AI助手

当前位置:首页 > 教育专区 > 其他

移动网页_全站_页脚广告1

关于我们      便捷服务       自信AI       AI导航        抽奖活动

©2010-2025 宁波自信网络信息技术有限公司  版权所有

客服电话:4009-655-100  投诉/维权电话:18658249818

gongan.png浙公网安备33021202000488号   

icp.png浙ICP备2021020529号-1  |  浙B2-20240490  

关注我们 :微信公众号    抖音    微博    LOFTER 

客服