您的位置:首页 > 编程语言 > Python开发

《python编程从入门到实践》 第4章习题选做

2018-03-15 23:18 411 查看
4-3 使用一个for循环打印数字1~20(含)for i in range(1, 21):
print(i)    执行结果:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
204-5 计算1~1 000 000的总和:创建一个列表,其中包含数字1~1 000 000,再使用min() 和max() 核实该列表确实是从1开始,到1 000 000结束的。另外,对这个列表 调用函数sum() ,看看Python将一百万个数字相加需要多长时间。import datetime

num_list = list(range(1, 1000001))
print(min(num_list))
print(max(num_list))
start = datetime.datetime.now()
print(sum(num_list))
end = datetime.datetime.now()
print("it takes "+str(end-start)+" seconds")    执行结果:1
1000000
500000500000
it takes 0:00:00.066645 seconds4-7 3的倍数:创建一个列表,其中包含3~30内能被3整除的数字;再使用一个for循环将这个列表中的数字都打印出来。num_list = list(range(3, 31, 3))
for num in num_list:
print(num)    执行结果:3
6
9
12
15
18
21
24
27
304-10 切片: 选择你在本章编写的一个程序,在末尾添加几行代码,以完成如下任务。(1)打印消息“The first three items in the list are:”,再使用切片来打印列表的前三个元素。(2)打印消息“Three items from the middle of the list are:”,再使用切片来打印列表中间的三个元素。(3)打印消息“The last three items in the list are:”,再使用切片来打印列表末尾的三个元素。num_list = [1,3,5,7,9,11,13]
print("The first three items in the list are:")
print(num_list[0:3])
print("Three items from the middle of the list are:")
print(num_list[2:5])
print("The last three items in the list are:")
print(num_list[-3:])    执行结果:The first three items in the list are:
[1, 3, 5]
Three items from the middle of the list are:
[5, 7, 9]
The last three items in the list are:
[9, 11, 13]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python