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

发布时间 : 星期三 文章《Python程序设计》习题与答案更新完毕开始阅读

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

第1章 基础知识

简单说明如何选择正确的Python版本。 答:

在选择Python的时候,一定要先考虑清楚自己学习Python的目的是什么,打算做哪方面的开发,有哪些扩展库可用,这些扩展库最高反复安装和卸载上。同时还应该注意,当更新的Python版本推出之后,不要急于更新,而是应该等确定自己所必须使用的扩展库也推出了较新版本之后再进行更新。

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

为什么说Python采用的是基于值的内存管理模式? 答:

Python采用的是基于值的内存管理方式,如果为不同变量赋值相同值,则在内存中只有一份该值,多个变量指向同一块内存地址,例如下面的代码。 >>> x = 3 >>> id(x) >>> y = 3 >>> id(y) >>> y = 5 >>> id(y) >>> id(x)

在Python中导入模块中的对象有哪几种方式? 答:常用的有三种方式,分别为

?import 模块名 [as 别名]

?from 模块名 import 对象名[ as 别名] ?from math import *

使用pip命令安装numpy、scipy模块。 答:在命令提示符环境下执行下面的命令: pip install numpy pip install scipy

编写程序,用户输入一个三位以上的整数,输出其百位以上的数字。例如用户输入1234,则程序输出12。(提示:使用整除运算。)

答:

x = input('Please input an integer of more than 3 digits:') try:

x = int(x) x = x else: print(x) except BaseException:

print('You must input an integer.') import types

x = input('Please input an integer of more than 3 digits:') if type(x) != :

print 'You must input an integer.' elif len(str(x)) != 4:

print 'You must input an integer of more than 3 digits.' else:

print xoin(map(str,result))

x = input('Please input an integer less than 1000:') t = x i = 2 result = [] while True: if t==1: break if t%i==0: (i) t = t/i else: i+=1

print x,'=','*'.join(map(str,result))

编写程序,至少使用2种不同的方法计算100以内所有奇数的和。 x = [i for i in range(1,100) if i%2==1] print(sum(x))

print(sum(range(1,100)[::2]))

编写程序,实现分段函数计算,如下表所示。

x y 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*x-2)

x<0 0 0<=x<5 x 5<=x<10 3x-5 10<=x<20 20<=x 0 第4章 字符串与正则表达式

假设有一段英文,其中有单独的字母“I”误写为“i”,请编写程序进行纠正。 1)不使用正则表达式

x = \ am not a businessman.\x = ('i ','I ') x = (' i ',' I ') print(x)

2)使用正则表达式

x = \ am not a businessman.\import re

pattern = (r'(?:[^\\w]|\\b)i(?:[^\\w])') while True: result = (x) if result: if (0) != 0:

x = x[:(0)+1]+'I'+x[(0)-1:] else:

x = x[:(0)]+'I'+x[(0)-1:] else: break print(x)

假设有一段英文,其中有单词中间的字母“i”误写为“I”,请编写程序进行纠正。 import re

x = \ am not a busInessman.\print(x)

pattern = (r'(?:[\\w])I(?:[\\w])') while True: result = (x) if result: if (0) != 0:

x = x[:(0)+1]+'i'+x[(0)-1:] else:

x = x[:(0)]+'i'+x[(0)-1:] else: break print(x)

有一段英文文本,其中有单词连续重复了2次,编写程序检查重复的单词并只保留一个。例如文本内容为“This is is a desk.”,程序输出为“This is a desk.”

联系合同范文客服:xxxxx#qq.com(#替换为@)