Python程序设计习题与答案 下载本文

内容发布更新时间 : 2024/5/13 6:39:03星期一 下面是文章的全部内容请认真阅读。

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

第1章 基础知识

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

在选择Python的时候,一定要先考虑清楚自己学习Python的目的是什么,打算做哪方面的开发,有哪些扩展库可用,这些扩展库最高支持哪个版本的Python,是Python 还是Python ,最高支持到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。(提示:使用整除运算。)

答:

1)Python 代码:

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.')

2)Python 代码:

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))

2)Python 代码

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以内所有奇数的和。

答:Python 代码如下,如果使用Python 只需要把其中的print()函数改为print语句即可。

x = [i for i in range(1,100) if i%2==1] print(sum(x))

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

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

x x<0 0<=x<5 5<=x<10 10<=x<20 20<=x y 0 x 3x-5 0 答:Python 代码如下,如果使用Python 只需要把其中的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*x-2)

第4章 字符串与正则表达式

假设有一段英文,其中有单独的字母“I”误写为“i”,请编写程序进行纠正。 答:这里给出Python 代码,如果使用Python 的话只需要修改其中的print()函数为print语句即可。

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”,请编写程序进行纠正。 答:这里给出Python 代码,如果使用Python 的话只需要修改其中的print()函数为print语句即可。

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: