《Python编程》第四章部分课后练习题

本文提供了一系列Python编程练习,包括打印1到20的数字、计算1到100万的总和、列出1到20之间的奇数、展示1到10之间数字的3倍数及立方,并对列表进行切片操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#4-3 数到20:

代码:

#4-3 数到20
for num in range(1, 21):
	print(num)

输出:pass


#4-5 计算1~1 000 000的总和:

代码:

#4-5 计算1~1 000 000的总和
import time

nums = list(range(1, 1000001))
print(min(nums))
print(max(nums))
time1 = time.clock()
print(sum(nums))  
time2 = time.clock()
message = 'It costs ' + str(time2 - time1) + 's'
print (message)

输出:

1
1000000
500000500000
It costs 0.1980368107604632s


#4-6 奇数:

代码:

#4-6 奇数
nums = list(range(1, 20, 2))
for num in nums:
	print(num)

输出:pass


#4-7 3的倍数:

代码:

#4-7 3的倍数
nums = list(i*3 for i in range(1, 11))
for num in nums:
	print(num)

输出:pass


#4-8 立方:

代码:

#4-8 立方
nums = list(i**3 for i in range(1, 11))
for num in nums:
	print(num)

输出:pass


#4-9 立方解析:

代码:

#4-9 立方解析
nums = list(i**3 for i in range(1, 11))
print(num)

输出:

[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]


#4-10 切片:

#4-10 切片
nums = list(i**3 for i in range(1, 11))
print(nums)
message = '\nThe first three items in the list are:'
print(message)
print(nums[:3])

message = '\nThree items from the middle of the list are:'
print(message)
print(nums[3:6])

message = '\nThe last three items in the list are:'
print(message)
print(nums[-3:])

输出:

[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

The first three items in the list are:
[1, 8, 27]

Three items from the middle of the list are:
[64, 125, 216]

The last three items in the list are:
[512, 729, 1000]

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值