Python语言程序设计(美-梁勇)第4章习题解答(英文)

合集下载

《Python程序设计》习题与答案-python教材答案

《Python程序设计》习题与答案-python教材答案

《Python法式设计》习题与参考谜底之老阳三干创作第1章基础知识1.1 简单说明如何选择正确的Python版本.答:在选择Python的时候,一定要先考虑清楚自己学习Python的目的是什么,筹算做哪方面的开发,有哪些扩展库可用,这些扩展库最高支持哪个版本的Python,是Python 2.x还是Python 3.x,最高支持到Python 2.7.6还是Python 2.7.9.这些问题都确定以后,再做出自己的选择,这样才华事半功倍,而不至于把年夜量时间浪费在Python的反复装置和卸载上.同时还应该注意,当更新的Python版本推出之后,不要急于更新,而是应该等确定自己所必需使用的扩展库也推出了较新版本之后再进行更新.尽管如此,Python 3究竟是年夜势所趋,如果您暂时还没想到要做什么行业领域的应用开发,或者仅仅是为了检验考试一种新的、好玩的语言,那么请毫不犹豫地选择Python 3.x系列的最高版本(目前是Python 3.4.3).1.2 为什么说Python采纳的是基于值的内存管理模式?答:Python采纳的是基于值的内存管理方式,如果为分歧变量赋值相同值,则在内存中只有一份该值,多个变量指向同一块内存地址,例如下面的代码.>>> x = 3>>> id(x)10417624>>> y = 3>>> id(y)10417624>>> y = 5>>> id(y)10417600>>> id(x)104176241.3 在Python中导入模块中的对象有哪几种方式?答:经常使用的有三种方式,分别为●import 模块名 [as 别名]●from 模块名 import 对象名[ as 别名]●from math import *1.4 使用pip命令装置numpy、scipy模块.答:在命令提示符环境下执行下面的命令:pip install numpypip install scipy1.5 编写法式,用户输入一个三位以上的整数,输出其百位以上的数字.例如用户输入1234,则法式输出12.(提示:使用整除运算.)答:1)Python 3.4.2代码:x = input('Please input an integer of more than 3 digits:')try:x = int(x)x = x//100if x == 0:print('You must input an integer of more than 3 digits.')else:print(x)except BaseException:print('You must input an integer.')2)Python 2.7.8代码:import typesx = input('Please input an integer of more than 3 digits:')if type(x) != types.IntType:print 'You must input an integer.'elif len(str(x)) != 4:print 'You must input an integer of more than 3 digits.'else:print x//100第2章 Python数据结构2.1 为什么应尽量从列表的尾部进行元素的增加与删除把持?答:当列表增加或删除元素时,列表对象自动进行内存扩展或收缩,从而保证元素之间没有缝隙,但这涉及到列表元素的移动,效率较低,应尽量从列表尾部进行元素的增加与删除把持以提高处置速度.2.2 编写法式,生成包括1000个0到100之间的随机整数,并统计每个元素的呈现次数.(提示:使用集合.)答:import randomx = [random.randint(0,100) for i in range(1000)]d = set(x)for v in d:print(v, ':', x.count(v))import randomx = [random.randint(0,100) for i in range(1000)]d = set(x)for v in d:print v, ':', x.count(v)2.3 编写法式,用户输入一个列表和2个整数作为下标,然后输出列表中介于2个下标之间的元素组成的子列表.例如用户输入[1,2,3,4,5,6]和2,5,法式输出[3,4,5,6].答:x = input('Please input a list:')x = eval(x)start, end = eval(input('Please input the start position and the end position:'))print(x[start:end])x = input('Please input a list:')start, end = input('Please input the start position and the end position:')print x[start:end]2.4 设计一个字典,并编写法式,用户输入内容作为键,然后输出字典中对应的值,如果用户输入的键不存在,则输出“您输入的键不存在!”答:d = {1:'a', 2:'b', 3:'c', 4:'d'}v = input('Please input a key:')v = eval(v)print(d.get(v,'您输入的的键不存在'))d = {1:'a', 2:'b', 3:'c', 4:'d'}v = input('Please input a key:')print(d.get(v,'您输入的的键不存在'))2.5 编写法式,生成包括20个随机数的列表,然后将前10个元素升序排列,后10个元素降序排列,并输出结果.答:import randomx = [random.randint(0,100) for i in range(20)]print(x)y = x[0:10]y.sort()x[0:10] = yy = x[10:20]y.sort(reverse=True)x[10:20] = yprint(x)import randomx = [random.randint(0,100) for i in range(20)]print xy = x[0:10]y.sort()x[0:10] = yy = x[10:20]y.sort(reverse=True)x[10:20] = yprint x2.6 在Python中,字典和集合都是用一对年夜括号作为定界符,字典的每个元素有两部份组成,即键和值 ,其中键不允许重复.2.7 假设有列表 a = ['name','age','sex']和 b = ['Dong',38,'Male'],请使用一个语句将这两个列表的内容转换为字典,而且以列表a中的元素为键,以列表b中的元素为值,这个语句可以写为 c = dict(zip(a,b)).2.8 假设有一个列表a,现要求从列表a中每3个元素取1个,而且将取到的元素组成新的列表b,可以使用语句 b = a[::3].2.9 使用列表推导式生成包括10个数字5的列表,语句可以写为 [5 for i in range(10)].2.10 不成以(可以、不成以)使用del命令来删除元组中的部份元素.第3章选择结构与循环结构3.1 分析逻辑运算符“or”的短路求值特性.答:假设有表达式“表达式1 or 表达式2”,如果表达式1的值等价于True,那么无论表达式2的值是什么,整个表达式的值总是等价于True.因此,不需要再计算表达式2的值.3.2 编写法式,运行后用户输入4位整数作为年份,判断其是否为闰年.如果年份能被400整除,则为闰年;如果年份能被4整除但不能被100整除也为闰年.答:x = input('Please input an integer of 4 digits meaning the year:')x = eval(x)if x%400==0 or (x%4==0 and not x%100==0):print('Yes')else:print('No')x = input('Please input an integer of 4 digits meaning the year:')if x%400==0 or (x%4==0 and not x%100==0):print 'Yes'else:print 'No'3.3 编写法式,生成一个包括50个随机整数的列表,然后删除其中所有奇数.(提示:从后向前删.)答:import randomx = [random.randint(0,100) for i in range(50)]print(x)i = len(x)-1while i>=0:if x[i]%2==1:del x[i]i-=1print(x)把上面的代码中第三行和最后一行改为print x即可.34 编写法式,生成一个包括20个随机整数的列表,然后对其中偶数下标的元素进行降序排列,奇数下标的元素不变.(提示:使用切片.)答:import randomx = [random.randint(0,100) for i in range(20)]print(x)y = x[::2]y.sort(reverse=True)x[::2] = yprint(x)把上面的代码中第三行和最后一行改为print x即可.35 编写法式,用户从键盘输入小于1000的整数,对其进行因式分解.例如,10=2×5,60=2×2×3×5.答:x = input('Please input an integer less than 1000:')x = eval('x')t = xi = 2result = []while True:if t==1:breakif t%i==0:result.append(i)t = t/ielse:i+=1Print x,'=','*'.join(map(str,result))x = input('Please input an integer less than 1000:')t = xi = 2result = []while True:if t==1:breakif t%i==0:result.append(i)t = t/ielse:i+=1print x,'=','*'.join(map(str,result))3.6 编写法式,至少使用2种分歧的方法计算100以内所有奇数的和.答:Python 3.4.2代码如下,如果使用Python 2.7.8只需要把其中的print()函数改为print语句即可.x = [i for i in range(1,100) if i%2==1]print(sum(x))print(sum(range(1,100)[::2]))3.7 编写法式,实现分段函数计算,如下表所示.答:Python 3.4.2代码如下,如果使用Python 2.7.8只需要把其中的print()函数改为print语句即可.x = input('Please input x:')x = eval(x)if x<0 or x>=20:print(0)elif 0<=x<5:print(x)elif 5<=x<10:print(3*x-5)elif 10<=x<20:print(0.5*x-2)第4章字符串与正则表达式4.1 假设有一段英文,其中有独自的字母“I”误写为“i”,请编写法式进行纠正.答:这里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要修改其中的print()函数为print语句即可.1)不使用正则表达式x = "i am a teacher,i am man, and i am 38 years old.I am not a businessman."x = x.WordStr('i ','I ')x = x.WordStr(' i ',' I ')print(x)2)使用正则表达式x = "i am a teacher,i am man, and i am 38 years old.I am not a businessman."import repattern = pile(r'(?:[^\w]|\b)i(?:[^\w])')while True:result = pattern.search(x)if result:if result.start(0) != 0:x = x[:result.start(0)+1]+'I'+x[result.end(0)-1:]else:x = x[:result.start(0)]+'I'+x[result.end(0)-1:]else:breakprint(x)4.2 假设有一段英文,其中有单词中间的字母“i”误写为“I”,请编写法式进行纠正.答:这里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要修改其中的print()函数为print语句即可.import rex = "I am a teacher,I am man, and I am 38 years old.I am not a busInessman."print(x)pattern = pile(r'(?:[\w])I(?:[\w])')while True:result = pattern.search(x)if result:if result.start(0) != 0:x = x[:result.start(0)+1]+'i'+x[result.end(0)-1:]else:x = x[:result.start(0)]+'i'+x[result.end(0)-1:]else:breakprint(x)4.3 有一段英文文本,其中有单词连续重复了2次,编写法式检查重复的单词并只保管一个.例如文本内容为“This is is a desk.”,法式输出为“This is a desk.”答:这里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要修改其中的print()函数为print语句即可.1)方法一import rex = 'This is a a desk.'pattern = pile(r'\b(\w+)(\s+\1){1,}\b') matchResult = pattern.search(x)x = pattern.sub(matchResult.group(1),x)print(x)2)方法二x = 'This is a a desk.'pattern = pile(r'(?P<f>\b\w+\b)\s(?P=f)') matchResult = pattern.search(x)x = x.WordStr(matchResult.group(0),matchResult.group(1))4.4 简单解释Python的字符串驻留机制.答:Python支持字符串驻留机制,即:对短字符串,将其赋值给多个分歧的对象时,内存中只有一个副本,多个对象共享该副本.这一点不适用于长字符串,即长字符串不遵守驻留机制,下面的代码演示了短字符串和长字符串在这方面的区别.>>> a = '1234'>>> b = '1234'>>> id(a) == id(b)True>>> a = '1234'*50>>> b = '1234'*50>>> id(a) == id(b)False4.5 编写法式,用户输入一段英文,然后输出这段英文中所有长度为3个字母的单词.答:这里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要修改其中的print()函数为print语句即可.import rex = input('Please input a string:')pattern = pile(r'\b[a-zA-Z]{3}\b')print(pattern.findall(x))第5章函数设计与使用5.1 运行5.3.1小节最后的示例代码,检查结果并分析原因.答:原因是对函数的默认值参数只会被处置一次,下次再调用函数而且不为默认值参数赋值时会继续使用上一次的结果,对列表这样的结构,如果调用函数时为默认值参数的列表拔出或删除元素,将会获得保管,从而影响下一次调用.5.2 编写函数,判断一个整数是否为素数,并编写主法式调用该函数.答:这里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要修改其中的print()函数为print语句即可.import mathdef IsPrime(v):n = int(math.sqrt(v)+1)for i in range(2,n):if v%i==0:return 'No'else:return 'Yes'print(IsPrime(37))print(IsPrime(60))print(IsPrime(113))5.3 编写函数,接收一个字符串,分别统计年夜写字母、小写字母、数字、其他字符的个数,并以元组的形式返回结果.答:这里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要修改其中的print()函数为print语句即可.def demo(v):capital = little = digit = other =0for i in v:if 'A'<=i<='Z':capital+=1elif 'a'<=i<='z':little+=1elif '0'<=i<='9':digit+=1else:other+=1return (capital,little,digit,other)x = 'capital = little = digit = other =0'print(demo(x))5.4 在Python法式中,局部变量会隐藏同名的全局变量吗?请编写代码进行验证.谜底:会.>>> def demo():a=3print a>>> a=5>>> demo()3>>> a55.5 编写函数,可以接收任意多个整数并输出其中的最年夜值和所有整数之和.答:这里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要修改其中的print()函数为print语句即可.def demo(*v):print(v)print(max(v))print(sum(v))demo(1,2,3)demo(1,2,3,4)demo(1,2,3,4,5)5.6 编写函数,模拟内置函数sum().答:这里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要修改其中的print()函数为print语句即可.def Sum(v):s = 0for i in v:s += ireturn sx = [1,2,3,4,5]print(Sum(x))x = (1,2,3,4,5)print(Sum(x))5.7 编写函数,模拟内置函数sorted().答:这里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要修改其中的print()函数为print语句即可.def Sorted(v):t = v[::]r = []while t:tt = min(t)r.append(tt)t.remove(tt)return rx = [1,3,5,2,1,0,9,7]print(x)print(Sorted(x))第6章面向对象法式设计6.1 继承6.5节例2中的Person类生成Student类,填写新的函数用来设置学生专业,然后生成该类对象并显示信息.import typesclass Person(object): #基类必需继承于object,否则在派生类中将无法使用super()函数def __init__(self, name = '', age = 20, sex = 'man'): self.setName(name)self.setAge(age)self.setSex(sex)def setName(self, name):if not isinstance(name,str):print('name must be string.')returnself.__name = namedef setAge(self, age):if not isinstance(age,int):print('age must be integer.')returnself.__age = agedef setSex(self, sex):if sex != 'man' and sex != 'woman':print('sex must be "man" or "woman"')returnself.__sex = sexdef show(self):print(self.__name)print(self.__age)print(self.__sex)class Student(Person):def __init__(self, name='', age = 30, sex = 'man', major = 'Computer'):#调用基类构造方法初始化基类的私有数据成员super(Student, self).__init__(name, age, sex)self.setMajor(major) #初始化派生类的数据成员def setMajor(self, major):if not isinstance(major, str):print('major must be a string.')returnself.__major = majordef show(self):super(Student, self).show()print(self.__major)if __name__ =='__main__':zhangsan = Person('Zhang San', 19, 'man')zhangsan.show()lisi = Student('Li Si',32, 'man', 'Math')lisi.show()6.2 设计一个三维向量类,并实现向量的加法、减法以及向量与标量的乘法和除法运算.class Vecter3:def __init__(self, x=0, y=0, z=0):self.X = xself.Y = yself.Z = zdef __add__(self, n):r = Vecter3()return rdef __sub__(self, n):r = Vecter3()return rdef __mul__(self, n):r = Vecter3()r.X = self.X * nr.Y = self.Y * nr.Z = self.Z * nreturn rdef __truediv__(self, n):r = Vecter3()r.X = self.X / nr.Y = self.Y / nr.Z = self.Z / nreturn rdef __floordiv__(self, n):r = Vecter3()r.X = self.X // nr.Y = self.Y // nr.Z = self.Z // nreturn rdef show(self):print((self.X,self.Y,self.Z))v1 = Vecter3(1,2,3)v2 = Vecter3(4,5,6)v3 = v1+v2v3.show()v4 = v1-v2v4.show()v5 = v1*3v5.show()v6 = v1/2v6.show()6.3 面向对象法式设计的三要素分别为封装、继承和多态 .6.4 简单解释Python中以下划线开头的变量名特点.答:在Python中,以下划线开头的变量名有特殊的含义,尤其是在类的界说中.用下划线作为变量前缀和后缀来暗示类的特殊成员:●_xxx:这样的对象叫做呵护变量,不能用'from moduleimport *'导入,只有类对象和子类对象能访问这些变量;●__xxx__:系统界说的特殊成员名字;●__xxx:类中的私有成员,只有类对象自己能访问,子类对象也不能访问到这个成员,但在对象外部可以通过“”这样的特殊方式来访问.Python中没有纯洁的C++意义上的私有成员.6.5 与运算符“**”对应的特殊方法名为__pow__(),与运算符“//”对应的特殊方法名为 __floordiv__() .第7章文件把持7.1 假设有一个英文文本文件,编写法式读取其内容,并将其中的年夜写字母酿成小写字母,小写字母酿成年夜写字母.答:f = open(r'd:\1.txt','r')s = f.readlines()f.close()r = [i.swapcase() for i in s]f = open(r'd:\2.txt','w')f.writelines(r)f.close()7.2 编写法式,将包括学生成果的字典保管为二进制文件,然后再读取内容并显示.import pickled = {'张三':98,'李四':90,'王五':100}print(d)f = open('score.dat','wb')pickle.dump(1,f)pickle.dump(d,f)f = open('score.dat','rb')pickle.load(f)d = pickle.load(f)f.close()print(d)7.3 使用shutil模块中的move()方法进行文件移动.答:>>> import shutil>>> shutil.move(r'd:\1.txt', r'e:\1.txt')'e:\\1.txt'7.4 简单解释文本文件与二进制文件的区别.答:(1)文本文件文本文件存储的是惯例字符串,由若干文本行组成,通常每行以换行符'\n'结尾.惯例字符串是指记事本或其他文本编纂器能正常显示、编纂而且人类能够直接阅读和理解的字符串,如英文字母、汉字、数字字符串.文本文件可以使用字处置软件如gedit、记事本进行编纂.(2)二进制文件二进制文件把对象内容以字节串(bytes)进行存储,无法用记事本或其他普通字处置软件直接进行编纂,通常也无法被人类直接阅读和理解,需要使用专门的软件进行解码后读取、显示、修改或执行.罕见的如图形图像文件、音视频文件、可执行文件、资源文件、各种数据库文件、各类office文档等都属于二进制文件.7.5 编写代码,将以后工作目录修改为“c:\”,并验证,最后将以后工作目录恢复为原来的目录.答:>>> import os>>> os.getcwd()。

XX医学院本科各专业《Python》第四章习题与答案-2020年精品

XX医学院本科各专业《Python》第四章习题与答案-2020年精品

XX医学院本科各专业《Python》第四章习题与答案一、填空题1.表达式'ab' in 'acbed' 的值为________。

(False)2.假设n为2,那么表达式n//1 == n%4 的值为_____________。

(True)3.Python通过保留字for实现“遍历循环”,之所以称为“遍历循环”,是因为for语句的循环执行次数是根据遍历结构中_____________确定的。

(元素个数)4.表达式3<5<2 的值为_______________。

(False)5.表达式1<2<3 的值为_________。

(True)6.表达式24<=28 and 28<25 的值为________。

(False)7.表达式24<=28 or 28<25 的值为_________。

(True)8.Python通过_____、_____、_____等保留字提供单分支、二分支和多分支。

(if elif else)9.当bmi的值为20时,表达式bmi<28 的值为______________。

(True)10.Python中用于表示逻辑与、逻辑或、逻辑非运算的保留字分别是_________、___________、_________。

(and、or、not)11.Python 3.x语句for i in range(3):print(i+1,end=',') 的输出结果为_____________________。

(1,2,3,)12.对于带有else子句的for循环和while循环,当循环因循环条件不成立而自然结束时________(会?不会?)执行else中的代码。

(会)13.在循环语句中,__________语句的作用是提前结束本层循环。

(break)14.在循环语句中,_______语句的作用是提前进入下一次循环。

《Python程序设计》习题与答案python教材答案

《Python程序设计》习题与答案python教材答案

《Python程序设计》习题与答案python教材答案《Python程序设计》习题与答案第一章:Python基础题目1:计算器程序设计答案:代码可以如下所示:```pythondef add(a, b):return a + bdef subtract(a, b):return a - bdef multiply(a, b):return a * bdef divide(a, b):if b == 0:return "Error: Division by zero is not allowed"return a / b```题目2:变量和数据类型答案:Python中的常见数据类型有整型(int)、浮点型(float)、字符串型(str)、布尔型(bool)等。

题目3:条件语句答案:条件语句用于根据不同的条件执行不同的代码块。

常见的条件语句有if语句、if-else语句和if-elif-else语句。

题目4:循环语句答案:循环语句用于多次执行相同或类似的代码块。

常见的循环语句有for循环和while循环。

第二章:函数和模块题目1:函数的定义和调用答案:函数是一段可重复使用的代码块,用于完成特定的任务。

函数的定义可以通过def关键字来实现,而函数的调用则通过函数名和参数完成。

题目2:内置函数答案:Python提供了丰富的内置函数,如print()、len()、input()等。

这些内置函数可以直接使用,无需额外定义。

题目3:模块的导入和使用答案:Python模块是一组相关的函数、类和变量的集合,用于组织、重用和扩展代码。

模块的导入可以使用import语句,然后通过模块名和函数名来调用模块中的内容。

第三章:文件操作题目1:文件的打开和关闭答案:文件操作前需要通过open()函数打开文件,在完成操作后需要使用close()函数关闭文件。

例如:```pythonfile = open("test.txt", "w")# 执行文件操作file.close()```题目2:读取文件内容答案:使用Python的read()函数可以读取整个文件的内容,或者使用readline()函数读取一行内容。

Python练习题及参考答案

Python练习题及参考答案

第1章Python概述一,选择题1.C 2.B二,填空题1.#2.IDLE三,简答题1.答:Python是解释型语言:计算机不能直接理解高级语言,只能直接理解机器语言。

使用解释型语言编写地源代码不是直接翻译成机器语言,而是先翻译成中间代码,再由解释器对中间代码进行解释运行。

因此使用Python编写地程序不需要翻译成二进制地机器语言,而是直接从源代码运行,过程如图1-3所示。

图1-3 Python程序地运行过程2.答:(1)简单易学:Python语言很简洁,语言也很简单,只需要掌握基本地英文单词就可以读懂Python程序。

这对于初学者无疑是个好消息。

因为简单就意味着易学,可以很轻松地上手。

(2)Python是开源地,免费地:开源是开放源代码地简称。

也就是说,用户可以免费获取Python地发布版本,阅读,甚至修改源代码。

很多志愿者将自己地源代码添加到Python中,从而使其日臻完善。

(3)Python是高级语言:与java与c一样,Pathon不依赖任何硬件系统,因此属于高级开发语言。

在使用Python开发应用程序时,不需要关注低级地硬件问题,例如内存管理。

(4)高可移植性:由于开源地缘故,Python兼容很多平台。

如果在编程时多加留意系统依赖地特性,Python程序无需进行任何修改,就可以在各种平台上运行。

Python支持地平台包括Linux, Windows, FreeBSD, Macintosh, Solaris, OS/2, Amiga, AROS, AS/400, BeOS,OS/390,z/OS, Palm OS, QNX,VMS,Psion,Acorn RISC OS,VxWorks,PlayStation,Sharp Zaurus,Windows CE与PocketPC。

(5)Python是解释型语言:计算机不能直接理解高级语言,只能直接理解机器语言。

使用解释型语言编写地源代码不是直接翻译成机器语言,而是先翻译成中间代码,再由解释器对中间代码进行解释运行。

python简明教程 第四章

python简明教程 第四章

简明 Python 教程第4章基本概念上一页字面意义上的常量下一页第4章基本概念目录表字面意义上的常量数字符串变量标识符的命名数据类型对象输出它如何工作逻辑行与物理行缩进概括仅仅打印“Hello World”就足够了吗?你应该想要做更多的事——你想要得到一些输入,然后做操作,再从中得到一些输出。

在Python中,我们可以使用常量和变量来完成这些工作。

字面意义上的常量一个字面意义上的常量的例子是如同5、1.23、9.25e-3这样的数,或者如同'This is a string'、"It's a string!"这样的字符串。

它们被称作字面意义上的,因为它们具备字面的意义——你按照它们的字面意义使用它们的值。

数2总是代表它自己,而不会是别的什么东西——它是一个常量,因为不能改变它的值。

因此,所有这些都被称为字面意义上的常量。

上一页上一级下一页概括首页数简明 Python 教程第4章基本概念上一页数下一页数在Python中有4种类型的数——整数、长整数、浮点数和复数。

∙2是一个整数的例子。

∙长整数不过是大一些的整数。

∙ 3.23和52.3E-4是浮点数的例子。

E标记表示10的幂。

在这里,52.3E-4表示52.3 * 10-4。

∙(-5+4j)和(2.3-4.6j)是复数的例子。

上一页上一级下一页字面意义上的首页字符串常量简明 Python 教程第4章基本概念上一页字符串下一页字符串字符串是字符的序列。

字符串基本上就是一组单词。

我几乎可以保证你在每个Python程序中都要用到字符串,所以请特别留心下面这部分的内容。

下面告诉你如何在Python中使用字符串。

∙使用单引号(')你可以用单引号指示字符串,就如同'Quote me on this'这样。

所有的空白,即空格和制表符都照原样保留。

∙使用双引号(")在双引号中的字符串与单引号中的字符串的使用完全相同,例如"What's your name?"。

Python程序设计答案和解析

Python程序设计答案和解析

一单选题 (共10题,每小题2分,总分值20)1. 答案:D2. 答案:C3. 答案:B4. 答案:D5. 答案:D6. 答案:B7. 答案:D8. 答案:A9. 答案:A10. 答案:B二多选题 (共5题,每小题3分,总分值15)11. 答案:A,B,C12. 答案:A,B13. 答案:A,B14. 答案:A,B,C15. 答案:A,B,C,D三判断 (共5题,每小题2分,总分值10)16. 答案:F17. 答案:T18. 答案:T19. 答案:T20. 答案:F四其他题 (共5题,每小题5分,总分值25)21. 答案:列表(list)是最重要的Python内置对象之一,是包含若干元素的有序连续内存空间。

在形式上,列表的所有元素放在一对方括号[]中,相邻元素之间使用逗号分隔。

在Python中,同一个列表中元素的数据类型可以各不相同,可以同时包含整数、实数、字符串等基本类型的元素,也可以包含列表、元组、字典、集合、函数以及其他任意对象。

如果只有一对方括号而没有任何元素则表示空列表。

22. 答案:集合(set)属于Python无序可变序列,使用一对大括号作为定界符,元素之间使用逗号分隔,同一个集合内的每个元素都是唯一的,元素之间不允许重复。

集合中只能包含数字、字符串、元组等不可变类型(或者说可哈希)的数据,而不能包含列表、字典、集合等可变类型的数据。

23. 答案:修饰器(decorator)是函数嵌套定义的另一个重要应用。

修饰器本质上也是一个函数,只不过这个函数接收其他函数作为参数并对其进行一定的改造之后使用新函数替换原来的函数。

Python面向对象程序设计中的静态方法、类方法、属性等也都是通过修饰器实现的。

24. 答案:私有成员在类的外部不能直接访问,一般是在类的内部进行访问和操作,或者在类的外部通过调用对象的公有成员方法来访问,而公有成员是可以公开使用的,既可以在类的内部进行访问,也可以在外部程序中使用。

《Python程序设计》习题与答案-python教材答案

《Python程序设计》习题与答案-python教材答案

《Python步调安排》习题与参照问案之阳早格格创做第1章前提知识1.1 简朴证明怎么样采用精确的Python版本.问:正在采用Python的时间,一定要先思量收会自己教习Python的手段是什么,挨算搞哪圆里的启垦,有哪些扩展库可用,那些扩展库最下支援哪个版本的Python,是Python 2.x仍旧Python 3.x,最下支援到Python 2.7.6仍旧Python 2.7.9.那些问题皆决定以去,再搞出自己的采用,那样才搞事半功倍,而不至于把洪量时间浪费正在Python的反复拆置战卸载上.共时还该当注意,当革新的Python版本推出之后,不要慢于革新,而是该当等决定自己所必须使用的扩展库也推出了较新版本之后再举止革新.纵然如许,Python 3到底是局势所趋,如果您姑且还出料到要搞什么止业范围的应用启垦,大概者只是是为了测验考查一种新的、佳玩的谈话,那么请当机立断天采用Python 3.x系列的最下版本(姑且是Python 3.4.3).1.2 为什么道Python采与的是鉴于值的内存管制模式?问:Python采与的是鉴于值的内存管制办法,如果为分歧变量赋值相共值,则正在内存中惟有一份该值,多个变量指背共一齐内存天面,比圆底下的代码.>>> x = 3>>> id(x)10417624>>> y = 3>>> id(y)10417624>>> y = 5>>> id(y)10417600>>> id(x)104176241.3 正在Python中导进模块中的对付象有哪几种办法?问:时常使用的有三种办法,分别为●import 模块名 [as 别号]●from 模块名 import 对付象名[ as 别号]●from math import *1.4 使用pip下令拆置numpy、scipy模块.问:正在下令提示符环境下真止底下的下令:pip install numpypip install scipy1.5 编写步调,用户输进一个三位以上的整数,输出其百位以上的数字.比圆用户输进1234,则步调输出12.(提示:使用整除运算.)问:1)Python 3.4.2代码:x = input('Please input an integer of more than 3 digits:')try:x = int(x)x = x//100if x == 0:print('You must input an integer of more than 3 digits.')else:print(x)except BaseException:print('You must input an integer.')2)Python 2.7.8代码:import typesx = input('Please input an integer of more than 3 digits:')if type(x) != types.IntType:print 'You must input an integer.'elif len(str(x)) != 4:print 'You must input an integer of more than 3 digits.'else:print x//100第2章 Python数据结构2.1 为什么应尽管从列表的尾部举止元素的减少与简略支配?问:当列表减少大概简略元素时,列表对付象自动举止内存扩展大概中断,进而包管元素之间不漏洞,但是那波及到列表元素的移动,效用较矮,应尽管从列表尾部举止元素的减少与简略支配以普及处理速度.2.2 编写步调,死成包罗1000个0到100之间的随机整数,并统计每个元素的出现次数.(提示:使用集中.)问:import randomx = [random.randint(0,100) for i in range(1000)]d = set(x)for v in d:print(v, ':', x.count(v))import randomx = [random.randint(0,100) for i in range(1000)]d = set(x)for v in d:print v, ':', x.count(v)2.3 编写步调,用户输进一个列表战2个整数动做下标,而后输出列表中介于2个下标之间的元素组成的子列表.比圆用户输进[1,2,3,4,5,6]战2,5,步调输出[3,4,5,6].问:x = input('Please input a list:')x = eval(x)start, end = eval(input('Please input the start position and the end position:')) print(x[start:end])x = input('Please input a list:')start, end = input('Please input the start position and the end position:')print x[start:end]2.4 安排一个字典,并编写步调,用户输进真质动做键,而后输出字典中对付应的值,如果用户输进的键不存留,则输出“您输进的键不存留!”问:d = {1:'a', 2:'b', 3:'c', 4:'d'}v = input('Please input a key:')v = eval(v)print(d.get(v,'您输进的的键不存留'))d = {1:'a', 2:'b', 3:'c', 4:'d'}v = input('Please input a key:')print(d.get(v,'您输进的的键不存留'))2.5 编写步调,死成包罗20个随机数的列表,而后将前10个元素降序排列,后10个元素落序排列,并输出截止.问:import randomx = [random.randint(0,100) for i in range(20)]print(x)y = x[0:10]y.sort()x[0:10] = yy = x[10:20]y.sort(reverse=True)x[10:20] = yprint(x)import randomx = [random.randint(0,100) for i in range(20)]print xy = x[0:10]y.sort()x[0:10] = yy = x[10:20]y.sort(reverse=True)x[10:20] = yprint x2.6 正在Python中,字典战集中皆是用一对付大括号动做定界符,字典的每个元素有二部分组成,即键战值,其中键不允许沉复.2.7 假设有列表a = ['name','age','sex']战b = ['Dong',38,'Male'],请使用一个语句将那二个列表的真质变换为字典,而且以列表a中的元素为键,以列表b中的元素为值,那个语句不妨写为 c = dict(zip(a,b)).2.8 假设有一个列表a,现央供从列表a中每3个元素与1个,而且将与到的元素组成新的列表b,不妨使用语句 b = a[::3].2.9 使用列表推导式死成包罗10个数字5的列表,语句不妨写为[5 for i in range(10)].2.10 不不妨(不妨、不不妨)使用del下令去简略元组中的部分元素.第3章采用结构与循环结构3.1 收会逻辑运算符“or”的短路供值个性.问:假设有表白式“表白式1 or 表白式2”,如果表白式1的值等价于True,那么无论表白式2的值是什么,所有表白式的值经常等价于True.果此,不需要再估计表白式2的值.3.2 编写步调,运止后用户输进4位整数动做年份,推断其是可为闰年.如果年份能被400整除,则为闰年;如果年份能被4整除但是不克不迭被100整除也为闰年.问:x = input('Please input an integer of 4 digits meaning the year:')x = eval(x)if x%400==0 or (x%4==0 and not x%100==0):print('Yes')else:print('No')x = input('Please input an integer of 4 digits meaning the year:')if x%400==0 or (x%4==0 and not x%100==0):print 'Yes'else:print 'No'3.3 编写步调,死成一个包罗50个随机整数的列表,而后简略其中所有奇数.(提示:从后背前删.)问:import randomx = [random.randint(0,100) for i in range(50)]print(x)i = len(x)-1while i>=0:if x[i]%2==1:del x[i]i-=1print(x)把上头的代码中第三止战末尾一止改为print x即可.34 编写步调,死成一个包罗20个随机整数的列表,而后对付其中奇数下目标元素举止落序排列,奇数下目标元素稳定.(提示:使用切片.)问:import randomx = [random.randint(0,100) for i in range(20)]print(x)y = x[::2]y.sort(reverse=True)x[::2] = yprint(x)把上头的代码中第三止战末尾一止改为print x即可.35 编写步调,用户从键盘输进小于1000的整数,对付其举止果式收会.比圆,10=2×5,60=2×2×3×5.问:x = input('Please input an integer less than 1000:')x = eval('x')t = xi = 2result = []while True:if t==1:breakif t%i==0:result.append(i)t = t/ielse:i+=1Print x,'=','*'.join(map(str,result))x = input('Please input an integer less than 1000:')t = xi = 2result = []while True:if t==1:breakif t%i==0:result.append(i)t = t/ielse:i+=1print x,'=','*'.join(map(str,result))3.6 编写步调,起码使用2种分歧的要收估计100以内所有奇数的战.问:Python 3.4.2代码如下,如果使用Python 2.7.8只需要把其中的print()函数改为print语句即可.x = [i for i in range(1,100) if i%2==1]print(sum(x))print(sum(range(1,100)[::2]))3.7 编写步调,真止分段函数估计,如下表所示.问:Python 3.4.2代码如下,如果使用Python 2.7.8只需要把其中的print()函数改为print语句即可.x = input('Please input x:')x = eval(x)if x<0 or x>=20:print(0)elif 0<=x<5:print(x)elif 5<=x<10:print(3*x-5)elif 10<=x<20:print(0.5*x-2)第4章字符串与正则表白式4.1 假设有一段英文,其中有单独的字母“I”误写为“i”,请编写步调举止纠正.问:那里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要建改其中的print()函数为print语句即可.1)不使用正则表白式x = "i am a teacher,i am man, and i am 38 years old.I am not a businessman." x = x.WordStr('i ','I ')x = x.WordStr(' i ',' I ')print(x)2)使用正则表白式x = "i am a teacher,i am man, and i am 38 years old.I am not a businessman." import repattern = pile(r'(?:[^\w]|\b)i(?:[^\w])')while True:result = pattern.search(x)if result:if result.start(0) != 0:x = x[:result.start(0)+1]+'I'+x[result.end(0)-1:]else:x = x[:result.start(0)]+'I'+x[result.end(0)-1:]else:breakprint(x)4.2 假设有一段英文,其中有单词汇中间的字母“i”误写为“I”,请编写步调举止纠正.问:那里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要建改其中的print()函数为print语句即可.import rex = "I am a teacher,I am man, and I am 38 years old.I am not a busInessman."print(x)pattern = pile(r'(?:[\w])I(?:[\w])')while True:result = pattern.search(x)if result:if result.start(0) != 0:x = x[:result.start(0)+1]+'i'+x[result.end(0)-1:]else:x = x[:result.start(0)]+'i'+x[result.end(0)-1:]else:breakprint(x)4.3 有一段英文文本,其中有单词汇连绝沉复了2次,编写步调查看沉复的单词汇并只死存一个.比圆文本真质为“This is is a desk.”,步调输出为“This is a desk.”问:那里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要建改其中的print()函数为print语句即可.1)要收一import rex = 'This is a a desk.'pattern = pile(r'\b(\w+)(\s+\1){1,}\b')matchResult = pattern.search(x)x = pattern.sub(matchResult.group(1),x)print(x)2)要收二x = 'This is a a desk.'pattern = pile(r'(?P<f>\b\w+\b)\s(?P=f)')matchResult = pattern.search(x)x = x.WordStr(matchResult.group(0),matchResult.group(1))4.4 简朴阐明Python的字符串驻留体制.问:Python支援字符串驻留体制,即:对付于短字符串,将其赋值给多个分歧的对付象时,内存中惟有一个副本,多个对付象共享该副本.那一面不适用于少字符串,即少字符串不按照驻留体制,底下的代码演示了短字符串战少字符串正在那圆里的辨别.>>> a = '1234'>>> b = '1234'>>> id(a) == id(b)True>>> a = '1234'*50>>> b = '1234'*50>>> id(a) == id(b)False4.5 编写步调,用户输进一段英文,而后输出那段英文中所有少度为3个字母的单词汇.问:那里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要建改其中的print()函数为print语句即可.import rex = input('Please input a string:')pattern = pile(r'\b[a-zA-Z]{3}\b')print(pattern.findall(x))第5章函数安排与使用5.1 运止5.3.1小节末尾的示例代码,查看截止并收会本果.问:本果是对付于函数的默认值参数只会被处理一次,下次再调用函数而且不为默认值参数赋值时会继启使用上一次的截止,对付于列表那样的结构,如果调用函数时为默认值参数的列表拔出大概简略了元素,将会得到死存,进而做用下一次调用.5.2 编写函数,推断一个整数是可为素数,并编写主步调调用该函数.问:那里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要建改其中的print()函数为print语句即可.import mathdef IsPrime(v):n = int(math.sqrt(v)+1)for i in range(2,n):if v%i==0:return 'No'else:return 'Yes'print(IsPrime(37))print(IsPrime(60))print(IsPrime(113))5.3 编写函数,交支一个字符串,分别统计大写字母、小写字母、数字、其余字符的个数,并以元组的形式返回截止.问:那里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要建改其中的print()函数为print语句即可.def demo(v):capital = little = digit = other =0for i in v:if 'A'<=i<='Z':capital+=1elif 'a'<=i<='z':little+=1elif '0'<=i<='9':digit+=1else:other+=1return (capital,little,digit,other)x = 'capital = little = digit = other =0'print(demo(x))5.4 正在Python步调中,局部变量会隐躲共名的齐部变量吗?请编写代码举止考证.问案:会.>>> def demo():a=3print a>>> a=5>>> demo()3>>> a55.5 编写函数,不妨交支任性多个整数并输出其中的最大值战所有整数之战.问:那里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要建改其中的print()函数为print语句即可.def demo(*v):print(v)print(max(v))print(sum(v))demo(1,2,3)demo(1,2,3,4)demo(1,2,3,4,5)5.6 编写函数,模拟内置函数sum().问:那里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要建改其中的print()函数为print语句即可.def Sum(v):s = 0for i in v:s += ireturn sx = [1,2,3,4,5]print(Sum(x))x = (1,2,3,4,5)print(Sum(x))5.7 编写函数,模拟内置函数sorted().问:那里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要建改其中的print()函数为print语句即可.def Sorted(v):t = v[::]r = []while t:tt = min(t)r.append(tt)t.remove(tt)return rx = [1,3,5,2,1,0,9,7]print(x)print(Sorted(x))第6章里背对付象步调安排6.1 继启6.5节例2中的Person类死成Student类,挖写新的函数用去树立教死博业,而后死成该类对付象并隐现疑息.import typesclass Person(object): #基类必须继启于object,可则正在派死类中将无法使用super()函数def __init__(self, name = '', age = 20, sex = 'man'):self.setName(name)self.setAge(age)self.setSex(sex)def setName(self, name):if not isinstance(name,str):print('name must be string.')returnself.__name = namedef setAge(self, age):if not isinstance(age,int):print('age must be integer.')returnself.__age = agedef setSex(self, sex):if sex != 'man' and sex != 'woman':print('sex must be "man" or "woman"')returnself.__sex = sexdef show(self):print(self.__name)print(self.__age)print(self.__sex)class Student(Person):def __init__(self, name='', age = 30, sex = 'man', major = 'Computer'):#调用基类构制要收初初化基类的公罕见据成员super(Student, self).__init__(name, age, sex)self.setMajor(major) #初初化派死类的数据成员def setMajor(self, major):if not isinstance(major, str):print('major must be a string.')returnself.__major = majordef show(self):super(Student, self).show()print(self.__major)if __name__ =='__main__':zhangsan = Person('Zhang San', 19, 'man')zhangsan.show()lisi = Student('Li Si',32, 'man', 'Math')lisi.show()6.2 安排一个三维背量类,并真止背量的加法、减法以及背量与标量的乘法战除法运算.class Vecter3:def __init__(self, x=0, y=0, z=0):self.X = xself.Y = yself.Z = zdef __add__(self, n):r = Vecter3()return rdef __sub__(self, n):r = Vecter3()return rdef __mul__(self, n):r = Vecter3()r.X = self.X * nr.Y = self.Y * nr.Z = self.Z * nreturn rdef __truediv__(self, n):r = Vecter3()r.X = self.X / nr.Y = self.Y / nr.Z = self.Z / nreturn rdef __floordiv__(self, n):r = Vecter3()r.X = self.X // nr.Y = self.Y // nr.Z = self.Z // nreturn rdef show(self):print((self.X,self.Y,self.Z))v1 = Vecter3(1,2,3)v2 = Vecter3(4,5,6)v3 = v1+v2v3.show()v4 = v1-v2v4.show()v5 = v1*3v5.show()v6 = v1/2v6.show()6.3 里背对付象步调安排的三果素分别为启拆、继启战多态 .6.4 简朴阐明Python中以下划线启头的变量名个性.问:正在Python中,以下划线启头的变量名有特殊的含意,更加是正在类的定义中.用下划线动做变量前缀战后缀去表示类的特殊成员:●_xxx:那样的对付象喊搞呵护变量,不克不迭用'from moduleimport *'导进,惟有类对付象战子类对付象能考察那些变量;●__xxx__:系统定义的特殊成员名字;●__xxx:类中的公有成员,惟有类对付象自己能考察,子类对付象也不克不迭考察到那个成员,但是正在对付象中部不妨通过“”那样的特殊办法去考察.Python中不杂粹的C++意思上的公有成员.6.5 与运算符“**”对付应的特殊要收名为__pow__(),与运算符“//”对付应的特殊要收名为 __floordiv__() .第7章文献支配7.1 假设有一个英文文本文献,编写步调读与其真质,并将其中的大写字母形成小写字母,小写字母形成大写字母.问:f = open(r'd:\1.txt','r')s = f.readlines()f.close()r = [i.swapcase() for i in s]f = open(r'd:\2.txt','w')f.writelines(r)f.close()7.2 编写步调,将包罗教死结果的字典死存为二进制文献,而后再读与真质并隐现.import pickled = {'弛三':98,'李四':90,'王五':100}print(d)f = open('score.dat','wb')pickle.dump(1,f)pickle.dump(d,f)f = open('score.dat','rb')pickle.load(f)d = pickle.load(f)f.close()print(d)7.3 使用shutil模块中的move()要收举止文献移动.问:>>> import shutil>>> shutil.move(r'd:\1.txt', r'e:\1.txt')'e:\\1.txt'7.4 简朴阐明文本文献与二进制文献的辨别.问:(1)文本文献文本文献死存的是惯例字符串,由若搞文本止组成,常常每止以换止符'\n'末端.惯例字符串是指记事本大概其余文本编写器能平常隐现、编写而且人类不妨曲交阅读战明白的字符串,如英笔墨母、汉字、数字字符串.文本文献不妨使用字处理硬件如gedit、记事本举止编写.(2)二进制文献二进制文献把对付象真质以字节串(bytes)举止死存,无法用记事本大概其余一般字处理硬件曲交举止编写,常常也无法被人类曲交阅读战明白,需要使用博门的硬件举止解码后读与、隐现、建改大概真止.罕睹的如图形图像文献、音视频文献、可真止文献、资材文献、百般数据库文献、百般office文档等皆属于二进制文献.7.5 编写代码,将目前处事目录建改为“c:\”,并考证,末尾将目前处事目录回复为本去的目录.问:>>> import os>>> os.getcwd()'C:\\Python34'。

C程序设计(双语版)习题答案

C程序设计(双语版)习题答案

第二章数据类型课后习题1.下列哪些是合法的变量名?如果合法,你认为它是一个好的助记符(能提醒你它的用途)吗?(a) stock_code 合法、好的助记符(b) money$ 非法,$为非法字符(c) Jan_Sales 合法、好的助记符(d) X-RAY 非法,–为非法字符(e) int 非法,int为关键字(f) xyz 合法、不是好的助记符(g) 1a 非法,变量名必须以字母或下划线打头(h) invoice_total合法、好的助记符(i) john's_exam_mark非法,’为非法字符(j) default 非法,default为关键字2.请确定下列常量的数据类型:(a) 'x' char(b) -39 int(c) 39.99 double(d) -39.0 double3.下列哪些是合法的变量定义?(a) integer account_code ; 非法,无integer类型(b) float balance ; 合法(c) decimal total ; 非法,无decimal类型(d) int age ; 合法(e) double int ; 非法,int为关键字,不能作为变量名(f) char c ; 合法4.写出下列各小题中的变量定义:(a) 整型变量number_of_transactions和age_in_yearsint number_of_transactions, age_in_years;(b) 单精度浮点型变量total_pay,tax_payment,distance和averagefloat total_pay, tax_payment, distance, average;(c) 字符型变量account_typechar account_type;(d) 双精度浮点型变量gross_paydouble gross_pay;5. 为下列各小题写出最合适的变量定义:(a) 班级中的学生人数int number_of_students;(b) 平均价格float average_price;(c) 自1900年1月1日以来的天数int days_since_1900;(d) 利率百分比float interest_rate;(e) 本页中最常出现的字符char most_common_char;(f) 中国的人口总数(在2010年11月大约为1,339,724,852)int population_of_china;6. 假定有如下定义:int i ;char c ;下面哪些是合法的C语句?c = 'A' ; 合法i = "1" ; 非法,字符串不能赋值给整型i = 1 ; 合法c = "A" ; 非法,”A”为字符串,存储为’A’和’\0’两个字符c = '1'; 合法7. 写一个C程序,给第4题中的变量各赋一个值,然后以每行一个变量的形式显示这些变量的值。

《Python程序设计》习题与答案-python教材答案

《Python程序设计》习题与答案-python教材答案

《Python程序设计》习题与参考答案之南宫帮珍创作第1章基础知识1.1 简单说明如何选择正确的Python版本。

答:在选择Python的时候,一定要先考虑清楚自己学习Python 的目的是什么,打算做哪方面的开发,有哪些扩展库可用,这些扩展库最高支持哪个版本的Python,是Python 2.x还是Python 3.x,最高支持到Python 2.7.6还是Python 2.7.9。

这些问题都确定以后,再做出自己的选择,这样才干事半功倍,而不至于把大量时间浪费在Python的反复装置和卸载上。

同时还应该注意,当更新的Python版本推出之后,不要急于更新,而是应该等确定自己所必须使用的扩展库也推出了较新版本之后再进行更新。

尽管如此,Python 3究竟是大势所趋,如果您暂时还没想到要做什么行业领域的应用开发,或者仅仅是为了测验考试一种新的、好玩的语言,那么请毫不犹豫地选择Python 3.x系列的最高版本(目前是Python 3.4.3)。

1.2 为什么说Python采取的是基于值的内存管理模式?答:Python采取的是基于值的内存管理方式,如果为分歧变量赋值相同值,则在内存中只有一份该值,多个变量指向同一块内存地址,例如下面的代码。

>>> x = 3>>> id(x)10417624>>> y = 3>>> id(y)10417624>>> y = 5>>> id(y)10417600>>> id(x)104176241.3 在Python中导入模块中的对象有哪几种方式?答:经常使用的有三种方式,分别为●import 模块名 [as 别号]●from 模块名 import 对象名[ as 别号]●from math import *1.4 使用pip命令装置numpy、scipy模块。

Python语言程序设计习题与答案

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.参数的值是否被改变,与函数中对变量的操作有关,与参数类型无关。

《python从入门到实践》--第四章基本操作列表重点及课后练习

《python从入门到实践》--第四章基本操作列表重点及课后练习

《python从⼊门到实践》--第四章基本操作列表重点及课后练习题⽬:4-1 ⽐萨:想出⾄少三种你喜欢的⽐萨,将其名称存储在⼀个列表中,再使⽤for 循环将每种⽐萨的名称都打印出来。

修改这个for 循环,使其打印包含⽐萨名称的句⼦,⽽不仅仅是⽐萨的名称。

对于每种⽐萨,都显⽰⼀⾏输出,如“I like pepperoni pizza”。

在程序末尾添加⼀⾏代码,它不在for 循环中,指出你有多喜欢⽐萨。

输出应包含针对每种⽐萨的消息,还有⼀个总结性句⼦,如“I really love pizza!”。

4-2 动物:想出⾄少三种有共同特征的动物,将这些动物的名称存储在⼀个列表中,再使⽤for 循环将每种动物的名称都打印出来。

修改这个程序,使其针对每种动物都打印⼀个句⼦,如“Adogwould makea great pet”。

在程序末尾添加⼀⾏代码,指出这些动物的共同之处,如打印诸如“Any oftheseanimals would makea great pet!”这样的句⼦。

代码:#!usr/bin/python# _*_ coding:utf-8 _*_pizzas = ["⽜⾁披萨","海鲜披萨","烤⾁披萨","鸡⾁披萨","番茄披萨"]for pizza in pizzas:#print(pizza)print("我喜欢吃" + pizza)print("总⽽⾔之,我真的很喜欢吃各种⼝味的披萨")animals = ["dog","elephonent","cat","pig"]for animal in animals:#print(animal)print("A "+ animal + " make me feel the beauty of life")print("Any of these animals make a great pet!")重点:⽣成⼀系列数字使⽤range()函数⽣成⼀系列的数字squares = []for num in range(1,21):#print(list(range(1,21)))#square = num**2 可以⽤可以不⽤,根据需求来#squares.append(square)#squares.append(num**2)print(squares,end="")#注意此地⽅的缩进,是否和for循环的语句属于同⼀代码块#列表解析⽤⼀⾏代码创建上⾯的平⽅数列表#使⽤这种语法,⾸先要指定⼀个列表名,如squares:然后,然后指定⼀个左⽅括号,并定义⼀个表达式#....⽤于⽣成你要存储到列表中的值。

2020年《python程序设计》基础知识及程序设计598题DU含参考答案

2020年《python程序设计》基础知识及程序设计598题DU含参考答案

2020年《python程序设计》基础知识及程序设计598题DU含参考答案2020年《Python程序设计》基础知识及程序设计598题目含参考答案本文旨在介绍2020年《Python程序设计》课程中的基础知识,并提供包含598道编程题目的参考答案。

Python程序设计是一门重要的计算机科学课程,是学习和掌握Python编程语言的关键。

通过学习本课程,学生将能够了解Python的基础知识,掌握编程技巧,并能够根据需要自主设计并实现各种有用的程序。

请按照以下内容继续阅读,了解本文的详细内容。

第一章:Python语言基础知识本章将介绍Python编程语言的基础知识,包括变量、数据类型、运算符、条件语句、循环语句等。

1.1 变量和数据类型Python中的变量用于存储数据,可以是数字、字符串、列表等。

变量的命名需要遵循一定的规则,如不能以数字开头,不能使用特殊字符等。

1.2 运算符Python中常用的运算符包括算术运算符、比较运算符、逻辑运算符等。

运算符可以用于对变量进行不同的操作。

1.3 条件语句条件语句用于根据条件的真假执行不同的代码块。

其中,常用的条件语句包括if语句、else语句和elif语句。

1.4 循环语句循环语句用于重复执行一段代码。

Python中的循环语句包括for循环和while循环。

第二章:Python程序设计本章将介绍Python程序设计的相关知识,包括函数、列表、字典、字符串处理等。

2.1 函数函数是一段可重用的代码块,可以接受输入参数并返回结果。

函数可以提高代码的可读性和可维护性,同时也能提高代码的效率。

2.2 列表列表是Python中常用的数据结构,可以存储多个元素,并且可以根据索引对列表进行访问和修改。

2.3 字典字典是一种键值对存储的数据结构,通过键来访问对应的值。

字典可以用于存储具有关联关系的数据。

2.4 字符串处理字符串处理在Python程序设计中非常重要,包括字符串的拼接、分割、替换等操作。

《Python程序设计》课后习题参考答案

《Python程序设计》课后习题参考答案

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

(2)不能使用空格、连字符、标点符号、引号等其他特殊字符。

(3)以字母或下划线开头,但不能以数字开头(4)严格区分大小写。

(5)要避免与Python关键字和函数名冲突2. 见表2.4.第3章3.4综合实验#1s1 = " keep on going never give up "s2 = s1.capitalize()print(s2)#2s3 = s2.strip()print(s3)#3print (s3.endswith('up'))#4print (s3.startswith('on'))#5print (s3.replace('e','aa'))#6print (s3.split('n'))#7print (s3.upper())#8n1 = 'Lily'print ('%s says: %s.'%(n1,s3))#9print (s3.center(40,'#'))#10print (s3.count('e'))#11print (s3.split())#12print ('/'.join(s4))#13print (' '.join(s4[::-1]))3.5 习题一、选择题1.B2.D3.C4.C二、填空题1. 'moon'2. 'shipfriend'3. 54. 'bEIjING'5. spam三、编程题1.str1 = 'I want to go to Beijing, Berli and Beijing this year. How about you?' str2 = str1.split()str2 = ' '.join(str2)print (str2)2.思路:(1).变量名的第一个字符是否为字母或下划线(2).如果是,继续判断--> 4(3).如果不是,报错(4).依次判断除了第一个字符之外的其他字符(5).判断是否为字母数字或者下划线while True:s = input('请输入字符(q退出):')if s == 'q':exit()#判断字符串第一个变量是否满足条件if s[0].isalpha() or s[0] == '_':for i in s[1:]:#判断判断除了第一个元素之外的其他元素是否满足条件if i.isalnum() or i == '_':continueelse:print('不合法')breakelse:print('合法')else:print('不合法')3.#!/usr/bin/env python#coding:utf-8s = input("输入:")s1 = s.split(" ")s2 = s1[0].upper()s3 = s1[-1].upper()print (s2.count(s3))4.s = input('input a string:\n')letters, space, digit, others = 0,0,0,0for c in s:if c.isalpha():letters += 1elif c.isspace():space += 1elif c.isdigit():digit += 1else:others += 1print ('char = %d,space = %d,digit = %d,others = %d' % (letters,space,digit,others))第4章4.4 综合实验#01fav_city = []#02fav_city.append('Qinghai')fav_city.append('Chengdu')fav_city.append('Dalian')fav_city.append('Xizang')fav_city.append('Haerbin')print (fav_city)#03fav_city[0] = 'Qingdao'#04fav_city.insert(2,'Kunming')#05del fav_city[0]#06fav_city.remove('Xizang')#07fav_city.sort()#08fav_city.reverse()#09for city1 in fav_city:print (city1)#10tuple_city = tuple(fav_city)#11len(tuple_city)4.5 习题一、选择题1.D2.A3.B4.D5.C二、填空题1.[123,22, 123,22]2.x = [1,3,5,7,9]3. [11,22,33,11]4. Flase5. b= [::2]6. (6,)三、编程题#1import randomx = [random.randint(0,100) for i in range(10)]x.sort()print (x)#2.list1 = ['Hollywood', 'Mexico', 'New Delhi', 'Tokyo'] item = list1.pop(0)list1.append(item)print (list1)#3a = int(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)x[5:] = sorted(x[5:])print (x)4.#列表推导法list1 = [22,11,33,22,44,33]temp_list=[]for x in list1:if x not in temp_list:temp_list.append(x)print (temp_list) #输出结果未排序#排序方法list1 = [22,11,33,22,44,33]list2 = sorted(list1)temp_list = []i = 0while i < len(list2):if list2[i] not in temp_list:temp_list.append(list2[i])else:i += 1print (temp_list) #输出结果已排序第5章字典综合实验1.Qing_Hai = ['qinghai','xining','青',8,'810000']Si_Chuan = ['sichuan','chengdu','川',21,'610000']Gan_Su = ['gansu','lanzhou','陇',14,'730000']Ning_Xia = ['ningxia','yinchuan','宁',5,'750000']Nei_MengGu = ['neimenggu','huhehaote','内蒙古',12,'010000'] Shaan_Xi = ['shaanxi','xian','陕',10,'710000']Shan_Xi = ['shanxi','taiyuan','晋',11,'030000']He_Nan = ['henan','zhengzhou','豫',18,'450000']Shan_Dong = ['shandong','jinan','鲁',16,'250000']provinces = [Qing_Hai,Si_Chuan,Gan_Su,Ning_Xia,Nei_MengGu,Shaan_Xi,Shan_Xi,He_Nan,Shan_Dong] Yellow_River_basin = {}for province in provinces:Yellow_River_basin[province[0]] = province[1:]print(Yellow_River_basin)2.# 遍历嵌套字典的键for key in Yellow_River_basin.keys():print(key)# 遍历嵌套字典的值for value in Yellow_River_basin.values():print(value)# 遍历嵌套字典的键值对for key, value in Yellow_River_basin.items():print(key+"'s Capital is : %s "%value[0]+" For_short is : %s "%value[1]+"Area_manage is : %d个"%value[2]+"Postal_code is : %s"%value[3])3.for provinc in Yellow_River_basin.keys():if provinc == 'sichuan':Yellow_River_basin[provinc] = ['chengdu', '蜀', 21, '610000']elif provinc == 'gansu':Yellow_River_basin[provinc] = ['lanzhou', '甘', 14, '730000']elif provinc == 'shaanxi':Yellow_River_basin[provinc][1] = '秦'print(Yellow_River_basin)4qinghai = {'name':'QingHai','capital':'XiNing','for_short':'青','area_manage':8}sichuang = {'name':'SiChuan','capital':'ChengDu','for_short':'川','area_manage':21}gansu = {'name':'GanSu','capital':'LanZhou','for_short':'陇','area_manage':14}ningxia = {'name':'NingXia','capital':'YinChuan','for_short':'宁','area_manage':5}neimenggu = {'name':'Neimenggu','capital':'HuheHaote','for_short':'内蒙古','area_manage':12} shaanxi= {'name':'ShaanXi','capital':'XiAn','for_short':'陕','area_manage':10}shanxi = {'name':'ShanXi','capital':'TaiYuan','for_short':'晋','area_manage':11}henan = {'name':'HeNan','capital':'ZhengZhou','for_short':'豫','area_manage':18}shandong = {'name':'ShanDong','capital':'JiNan','for_short':'鲁','area_manage':16}basin_list = [qinghai,sichuang,gansu,ningxia,neimenggu,shaanxi,shanxi,henan,shandong] Postal_Code = ['810000','610000','730000','750000','010000','710000','030000','450000','250000']print(basin_list)5for province_num in range(len(basin_list)):basin_list[province_num]['postal_code'] = Postal_Code[province_num]print(basin_list)第5章综合实验一、选择题1.B2.C3.B4.D5.D二、简答题1.(1)字典的键(key)具有唯一性。

python编程快速上手之第4章实践项目参考答案

python编程快速上手之第4章实践项目参考答案

python编程快速上⼿之第4章实践项⽬参考答案 1#!/usr/bin/env python3.52# coding:utf-83# 假定有⼀个列表,编写函数以⼀个列表值作为参数,返回⼀个字条串4# 该字符串包含所有表项,之间以逗号和空格分隔,并在最后⼀个值前插⼊ and5# 要求函数能处理传递给它的任何列表67# spam = input('please input a list:')8# 刚开始想从⽤户输⼊进⾏传递列表⽅式,但没成功910# 4.10.111print("4.10.1 answer:")12def chlist_str(spam):13 spam[-1] = 'and ' + spam[-1]14 str_list = ', '.join(spam)15return str_list16 new_str = chlist_str(['apple','banana','tofu','cats'])17print("convert str is:")18print(new_str)1920# 4.10.221# 这道题的⽬的在于进⾏嵌套列表的⾏列转换吧22print("4.10.2 answer:")23 grid = [['.','.','.','.','.','.'],24 ['.','o','o','.','.','.'],25 ['o','o','o','o','.','.'],26 ['o','o','o','o','o','.'],27 ['.','o','o','o','o','o'],28 ['o','o','o','o','o','.'],29 ['o','o','o','o','.','.'],30 ['.','o','o','.','.','.'],31 ['.','.','.','.','.','.']]3233# 第⼀种实现⽅法,因为这个列表的⾏列长度不相等,外层循环的换⾏数应该是⼦列表的长度。

《Python编程:从入门到实践》第四章操作列表习题答案

《Python编程:从入门到实践》第四章操作列表习题答案

《Python编程:从⼊门到实践》第四章操作列表习题答案#4.1pizzas = ['KFC','MDL','DKS']'''1'''for pizza in pizzas:print(pizza);'''2'''for pizza in pizzas:print("I like "+ pizza +" pizza!")'''3'''print("My favourite pizza is KFC and I really love pizza!")#4.2animals = ['cat','tiger','dog']'''1'''for animal in animals:print(animal)'''2'''for animal in animals:print("A " + animal +" would like a great pet!")'''3'''print("Any of these animals would like a great pet!")#4.3for i in range(1,21):print(i)#4.4numberList = []for i in range(1,1000001):numberList.append(i)print(numberList)#4.5numberList = []for i in range(1,1000001):numberList.append(i)print(min(numberList))print(max(numberList))print(sum(numberList))#4.6oddNumber = []for odd in range(1,21,2):oddNumber.append(odd)for odd in oddNumber:print(odd)#4.7divideByThere = []for i in range(3,31,3):divideByThere.append(i)for i in divideByThere:print(i)#4.8number = []for i in range(1,11):number.append(i**3)for i in number:print(i)#4.9cube = [i**3 for i in range(1,11)]print(cube)#4.10cube = [i**3 for i in range(1,11)]print("The first there items in the list are:" + str(cube[0:3]))print("The items from the middle of the list are:" + str(cube[4:7]))print("The last there items in the list are:" + str(cube[-3:]))#4.11pizzas = ['KFC','MDL','DKS']friend_pizzas = pizzas[:]print(friend_pizzas)pizzas.append('JGM')friend_pizzas.append('BSK')print("My favourite pizzas are:")for pizza in pizzas:print(pizza)print("My friend's favourite pizzas are:")for pizza in friend_pizzas:print(pizza)#4.12略#4.13foods = ('noodle','humburger','pizza','donut','sanwiches') for food in foods:print(food)#foods(0) ='egg'foods = ('egg','humburger','pizza','donut','dumplings') print(foods)#4.14略#4.15略。

Python语言程序设计(美-梁勇)第4章习题解答(英文)

Python语言程序设计(美-梁勇)第4章习题解答(英文)

Chapter 4 Selections1. <, <=, ==, !=, >, >=2. Yes. i becomes 1, j becomes 0, b1 becomes True, and b2 becomes Flase.3. random.randrange(0, 20) or random.randint(0, 19)4. random.randrange(10, 20) or random.randint(10, 19)5. random.randrange(10, 50 + 1) or random.randint(10, 50)6. random.randrange(0, 2) or random.randint(0, 1)7.if y > 0:x = 18.if score > 90:pay *= 1.039.if score > 90:pay *= 1.03else:pay *= 1.0110.If number is 30,(a) displays30 is even30 is odd(b) displays30 is evenIf number is 35,(a) displays35 is odd(b) displays35 is odd11. Note: else matches the second if clause. The output is “x is 3” if x = 3 and y = 2. The o utput is “z is 7” if if x = 3 and y = 4. No output if if x = 2 and y = 2.12. Note: else matches the first if clause. The output is “x is 2” if x = 2 and y = 4. No output if if x = 3 and y = 2.The output is “z is 6” if if x = 3 and y = 3.13.Consider score is 90, what will be the grade? The conditions are tested in the wrong orders.14.(A) and (C) are equivalent. (B) and (D) are incorrectly indented.15.newLine = (count % 10 == 0)16.Both are correct. (B) is better. Both conditions in (A) are tested. In (B) the condition is tested only once.17.For number is 14, (a) displays:14 is even(b) displays14 is evenFor number is 15, (a) displays:15 is multiple of 5(b) displays15 is multiple of 5For number is 30, (a) displays:30 is even30 is multiple of 5(b) displays30 is even18.Yes19.This program will have a runtime error, because tax will not be created.20. (true) and (3 > 4)Falsenot(x > 0) and (x > 0)False(x > 0) or (x < 0)True(x != 0) or (x == 0)True(x >= 0) or (x < 0)True(x != 1) == not (x == 1)True21. (x > 1) and (x < 100)22. ((x > 1) and (x < 100)) or (x < 0)23.x >= y >= 0 Falsex <= y >= 0 Truex != y == 5 True(x != 0) or (x == 0) True24.Yes25.If ch is 'A', the expression is true;If ch is 'p', the expression is false;If ch is 'E', the expression is true;If ch is '5', the expression is false;26.(x < y and y < z) is True(x < y or y < z) is Truenot (x < y) is False(x < y < z) is Truenot (x < y < z) is False27. age > 13 and age < 1828.weight > 50 or height > 160.29.weight > 50 and height > 160.30.(weight > 50 or height > 160) and not (weight > 50 and height > 160)31. Sorted32.ticketPrice = 20 if (ages >= 16) else 10print(count, end = "\n" if count % 10 == 0 else " ")33.A:if x > 10:score = 3 * scaleelse:score = 4 * scaleB:if income > 10000:tax = income * 0.2else:tax = income * 0.17 + 1000C:if number % 3 == 0:print(i)else:print(j)34.The precedence order of the Boolean operators are not, and, or in this order.TrueTrue35.True36.2 * 2 -3 > 2 and 4–2 > 5 False2 * 2 -3 > 2 or 4–2 > 5 False 37.Yes. Yes. Yes.。

Python程序设计(英语)智慧树知到课后章节答案2023年下中央财经大学

Python程序设计(英语)智慧树知到课后章节答案2023年下中央财经大学

Python程序设计(英语)智慧树知到课后章节答案2023年下中央财经大学第一章测试1.What is the fundamental question of computer science? ()A:How muchmoney can a programmer make? B:What can be computed? C:What is themost effective programming language? D:How fast can a computer compute?答案:What can be computed?2. A statement is ()A:a precise description of a problem B:a completecomputer command C:a section of an algorithm D:a translation of machinelanguage 答案:a complete computer command3.The items listed in the parentheses of a function definition are called ()A:parentheticals B:both B and C are correct C:parameters D:arguments 答案:both B and C are correct4.All information that a computer is currently working on is stored in mainmemory. ()A:对 B:错答案:对5. A loop is used to skip over a section of a program. ()A:错 B:对答案:错第二章测试1.Which of the following is not a legal identifier?()A:spAm B:2spamC:spam D:spam4U 答案:spam2.In Python, getting user input is done with a special expression called ()A:simultaneous assignment B:input C:for D:read 答案:input3.The process of describing exactly what a computer program will do to solve aproblem is called ()A:specification B:programming C:DesignD:implementation 答案:specification4.In Python, x = x + 1 is a legal statement. ()A:错 B:对答案:对5.The best way to write a program is to immediately type in some code andthen debug it until it works. ()A:对 B:错答案:错第三章测试1.Which of the following is not a built-in Python data type? ()A:intB:rational C:string D:float 答案:rational2.The most appropriate data type for storing the value of pi is ()A:stringB:int C:float D:irrational 答案:float3.The pattern used to compute factorials is ()A:input, process, outputB:accumulator C:counted loop D:plaid 答案:accumulator4.In Python, 4+5 produces the same result type as 4.0+5.0. ()A:对 B:错答案:错5.Definite loops are loops that execute a known number of times. ()A:对 B:错答案:对第四章测试1. A method that changes the state of an object is called a(n) ()A:functionB:constructor C:mutator D:accessor 答案:mutator2.Which of the following computes the horizontal distance between points p1and p2? ()A:abs(p1.getX( ) - p2.getX( )) B:abs (p1-p2) C:p2.getX( ) -p1.getX( ) D:abs(p1.getY( ) - p2.getY( )) 答案:abs(p1.getX( ) - p2.getX( ))3.What color is color_rgb (0,255,255)? ()A:Cyan B:Yellow C:MagentaD:Orange 答案:Cyan4.The situation where two variables refer to the same object is called aliasing.()A:错 B:对答案:对5. A single point on a graphics screen is called a pixel. ()A:错 B:对答案:对第五章测试1.Which of the following is the same as s [0:-1]? ()A:s[:] B:s[:len(s)-1] C:s[-1]D:s[0:len(s)] 答案:s[:len(s)-1]2.Which of the following cannot be used to convert a string of digits into anumber? ()A:int B:eval C:str D:float 答案:str3.Which string method converts all the characters of a string to upper case? ()A:capwords B:upper C:capitalize D:uppercase 答案:upper4.In Python “4”+“5”is “45”. ()A:错 B:对答案:对5.The last character of a strings is at position len(s)-1. ()A:错 B:对答案:对第六章测试1. A Python function definition begins with ()A:def B:define C:defunD:function 答案:def2.Which of the following is not a reason to use functions? ()A:todemonstrate intellectual superiority B:to reduce code duplication C:to makea program more self-documenting D:to make a program more modular 答案:to demonstrate intellectual superiority3. A function with no return statement returns ()A:its parameters B:nothingC:its variables D:None 答案:None4.The scope of a variable is the area of the program where it may be referenced.()A:对 B:错答案:对5.In Python, a function can return only one value. ()A:对 B:错答案:错第七章测试1.In Python, the body of a decision is indicated by ()A:indentation B:curlybraces C:parentheses D:a colon 答案:indentation2.Placing a decision inside of another decision is an example of ()A:procrastination B:spooning C:cloning D:nesting 答案:nesting3.Find a correct algorithm to solve a problem and then strive for ()A:clarityB:efficiency C:scalability D:simplicity 答案:clarity;efficiency;scalability;simplicity4.Some modules, which are made to be imported and used by other programs,are referred to as stand-alone programs. ()A:对 B:错答案:错5.If there was no bare except at the end of a try statement and none of theexcept clauses match, the program would still crash. ()A:对 B:错答案:对第八章测试1. A loop pattern that asks the user whether to continue on each iteration iscalled a(n) ()A:end-of-file loop B:sentinel loop C:interactive loopD:infinite loop 答案:interactive loop2. A loop that never terminates is called ()A:indefinite B:busy C:infiniteD:tight 答案:infinite3.Which of the following is not a valid rule of Boolean algebra? ()A:a and (bor c) == (a and b) or (a and c) B:(True or False) == True C:not(a and b)==not(a) and not(b) D:(True or x) == True 答案:not(a and b)== not(a) andnot(b)4.The counted loop pattern uses a definite loop. ()A:错 B:对答案:对5. A sentinel loop should not actually process the sentinel value. ()A:错 B:对答案:对第九章测试1.()A:random() >= 66 B:random() < 0.66 C:random() < 66 D:random() >= 0.66 答案:random() < 0.662.The arrows in a module hierarchy chart depict ()A:control flow B:one-way streets C:logistic flow D:information flow 答案:information flow3.In the racquetball simulation, what data type is returned by the gameOverfunction? ()A:bool B:string C:float D:int 答案:bool4. A pseudorandom number generator works by starting with a seed value. ()A:错 B:对答案:对5.Spiral development is an alternative to top-down design. ()A:错 B:对答案:错第十章测试1. A method definition is similar to a(n) ()A:module B:import statementC:function definition D:loop 答案:function definition2.Which of the following methods is NOT part of the Button class in thischapter? ()A:activate B:clicked C:setLabel D:deactivate 答案:setLabel3.Which of the following methods is part of the DieView class in this chapter?()A:setColor B:clicked C:setValue D:activate 答案:setValue4.New objects are created by invoking a constructor. ()A:对 B:错答案:对5.A:错 B:对答案:错第十一章测试1.The method that adds a single item to the end of a list is ()A:plus B:addC:append D:extend 答案:append2.Which of the following expressions correctly tests if x is even? ()A:not odd(x) B:x % 2 == 0 C:x % 2 == x D:even (x) 答案:x % 2 == 03.Items can be removed from a list with the del operator. ()A:错 B:对答案:对4.Unlike strings, Python lists are not mutable. ()A:对 B:错答案:错5.()A:对 B:错答案:错第十二章测试1.Which of the following was NOT a class in the racquetball simulation? ()A:SimStats B:Player C:RBallGame D:Score 答案:Score2.What is the data type of server in an RBallGame? ()A:SimStats B:bool C:intD:Player 答案:Player3.The setValue method redefined in ColorDieView class is an example of ()A:polymorphism B:generality C:encapsulation D:inheritance 答案:polymorphism;inheritance4.Hiding the details of an object in a class definition is called instantiation. ()A:对 B:错答案:错5.Typically, the design process involves considerable trial and error. ()A:错B:对答案:对。

Python基础及应用习题答案4

Python基础及应用习题答案4

1.统计英文句子 "python is an interpreted language" 有多少个单词。

print("please enter a sentence")x=input()print("the number of the word is",x.count(" ")+1)2.统计英文句子 "python is an interpreted language" 有多少个字母'a'。

a='python is an interpreted language'a.replace(' ','')x=0for i in range(len(a)):if a[i]=='a':x+=1print('a=',x)3.使用 input 输入一个字符串,遍历每一个字符来判断它是不是全是小写英文字母或者数字。

print("please enter a string")x=input()x=str(x)y=len(x)for i in range(0,y):if ord(x[i])>=48 and ord(x[i])<=57 or ord(x[i])>=97 and ord(x[i])<=122:flag=1else:flag=0breakif flag==1:print("yes")else:print("no")4.输入一个字符串,反转它并输出。

a=input()list=[]for i in range(len(a)):list.append(a[len(a)-1-i])b=''.join(list)print(b)5.统计一个英文字符串中每个字母出现的次数。

Python语言程序设计(美-梁勇)第4章选择习题解答

Python语言程序设计(美-梁勇)第4章选择习题解答

第4章选择4.1列举六种比较运算符。

答:<,>,==,!=,<=,>=。

4.2下面的转换是允许的吗?如果允许,给出转换后的结果。

i = int(True) 1j = int(False) 0B1 = bool(4) trueB2 = bool(0) false4.3怎样生成一个满足条件0<= i< 20的随机整数?答:random.randrange(0, 20)4.4怎样生成一个满足条件10<= i < 20的随机整数?答:random.randrange(10, 20)4.5怎样生成一个满足条件10<= i<= 50的随机整数?答:random.randint(10, 50)4.6怎样生成一个值为0或1的随机整数?答:random.randint(0, 1)4.7编写一个如果y大于零,将1赋值给x的if语句。

答:if y > 1 :X = 14.8编写一个如果score > 90,pay增长3%的if语句。

答:if score > 90:Pay *= (1 + 3%)4.9编写一个如果score大于90,pay上涨3%,否则上涨1%的语句。

答:if score > 90:Pay *= (1 + 3%)Else:Pay *= (1 + 1%)4.10如果number分别是30和35,那么a中的代码和b中的代码输出结果是什么?If number % 2 == 0: if number % 2 == 0: Print(number, “is even.”) print(number, “is even.”) Print(number, “is odd.”) else:Print(number, “is odd.”)A B答:If number is 30, (a)30 is even30 is odd(b)30 is evenIf number is 35, (a) 35 is odd(b)35 is odd4.114.124.13下面的代码错在哪里?if score >=60.0:Grade = ‘D’Elif score >= 70.0:Grade = ‘C’Elif score >= 80.0:Grade = ‘B’Elif score >= 90.0:Grade = ‘A’答:顺序反了。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Chapter 4 Selections
1. <, <=, ==, !=, >, >=
2. Yes. i becomes 1, j becomes 0, b1 becomes True, and b2 becomes Flase.
3. random.randrange(0, 20) or random.randint(0, 19)
4. random.randrange(10, 20) or random.randint(10, 19)
5. random.randrange(10, 50 + 1) or random.randint(10, 50)
6. random.randrange(0, 2) or random.randint(0, 1)
7.
if y > 0:
x = 1
8.
if score > 90:
pay *= 1.03
9.
if score > 90:
pay *= 1.03
else:
pay *= 1.01
10.
If number is 30,
(a) displays
30 is even
30 is odd
(b) displays
30 is even
If number is 35,
(a) displays
35 is odd
(b) displays
35 is odd
11. Note: else matches the second if clause. The output is “x is 3” if x = 3 and y = 2. The o utput is “z is 7” if if x = 3 and y = 4. No output if if x = 2 and y = 2.
12. Note: else matches the first if clause. The output is “x is 2” if x = 2 and y = 4. No output if if x = 3 and y = 2.The output is “z is 6” if if x = 3 and y = 3.
13.
Consider score is 90, what will be the grade? The conditions are tested in the wrong orders.
14.
(A) and (C) are equivalent. (B) and (D) are incorrectly indented.
15.
newLine = (count % 10 == 0)
16.
Both are correct. (B) is better. Both conditions in (A) are tested. In (B) the condition is tested only once.
17.
For number is 14, (a) displays:
14 is even
(b) displays
14 is even
For number is 15, (a) displays:
15 is multiple of 5
(b) displays
15 is multiple of 5
For number is 30, (a) displays:
30 is even
30 is multiple of 5
(b) displays
30 is even
18.
Yes
19.
This program will have a runtime error, because tax will not be created.
20. (true) and (3 > 4)
False
not(x > 0) and (x > 0)
False
(x > 0) or (x < 0)
True
(x != 0) or (x == 0)
True
(x >= 0) or (x < 0)
True
(x != 1) == not (x == 1)
True
21. (x > 1) and (x < 100)
22. ((x > 1) and (x < 100)) or (x < 0)
23.
x >= y >= 0 False
x <= y >= 0 True
x != y == 5 True
(x != 0) or (x == 0) True
24.
Yes
25.
If ch is 'A', the expression is true;
If ch is 'p', the expression is false;
If ch is 'E', the expression is true;
If ch is '5', the expression is false;
26.
(x < y and y < z) is True
(x < y or y < z) is True
not (x < y) is False
(x < y < z) is True
not (x < y < z) is False
27. age > 13 and age < 18
28.
weight > 50 or height > 160.
29.
weight > 50 and height > 160.
30.
(weight > 50 or height > 160) and not (weight > 50 and height > 160)
31. Sorted
32.
ticketPrice = 20 if (ages >= 16) else 10
print(count, end = "\n" if count % 10 == 0 else " ")
33.
A:
if x > 10:
score = 3 * scale
else:
score = 4 * scale
B:
if income > 10000:
tax = income * 0.2
else:
tax = income * 0.17 + 1000
C:
if number % 3 == 0:
print(i)
else:
print(j)
34.
The precedence order of the Boolean operators are not, and, or in this order.
True
True
35.
True
36.
2 * 2 -
3 > 2 and 4–2 > 5 False
2 * 2 -
3 > 2 or 4–2 > 5 False 37.
Yes. Yes. Yes.。

相关文档
最新文档