《Python程序设计》习题与答案python教材答案
![《Python程序设计》习题与答案python教材答案](https://img.360docs.net/img1a/132mm1roonayynli0a0vrt19aoxu0qow-a1.webp)
![《Python程序设计》习题与答案python教材答案](https://img.360docs.net/img1a/132mm1roonayynli0a0vrt19aoxu0qow-42.webp)
《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)
>>> y = 3
>>> id(y)
>>> y = 5
>>> id(y)
>>> id(x)
1、3 在Python中导入模块中的对象有哪几种方式?
答:常用的有三种方式,分别为
import 模块名[as 别名]
●from 模块名import 对象名[ as 别名]
●from math import *
1、4 使用pip命令安装numpy、scipy模块。
答:在命令提示符环境下执行下面的命令:
pip install numpy
pip install scipy
1、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//100
if 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 types
x = 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之间的随机整数,并统计每个元素的出现次数。(提示:使用集合。)
答:
1)Python 3、4、2代码
import random
x = [random、randint(0,100) for i in range(1000)]
d = set(x)
for v in d:
print(v, ':', x、count(v))
2)Python 2、7、8代码
import random
x = [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]。
答:
1)Python 3、4、2代码
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])
2)Python 2、7、8代码