高级编程技术作业_5

4-3 数到20

题目描述:使用一个for循环打印数字1~20(包含)

代码展示

for number in range(1,21):
    print(number)

INPUT
null

OUTPUT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

4-6 奇数

题目描述:通过给函数range()指定第三个参数来创建一个列表,其中包含1~20的奇数,再使用一个
for循环将这些数打印出来。

代码展示

l = list(range(1,21,2))
for number in l:
    print(number)

INPUT
null

OUTPUT
1
3
5
7
9
11
13
15
17
19

4-9 立方解析

题目描述:使用列表解析生成一个列表,其中包含前十个整数的立方。

代码展示:

l = [value**3 for value in range(1,11)]

INPUT
null

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

4-10 切片

题目描述:选择本章一个程序,在末尾添加几行代码,完成如下任务:
·打印消息"The first three items in the list are:",再使用切片来打印列表前三个元素
·打印消息"Three items from the middle of the list are:",再使用切片来打印列表的中间的三个元素
·打印消息"The last three items in the list are:",在使用切片来打印列表末尾的三个元素。

代码展示:

l = [value**3 for value in range(1,11)]

print("The first three items in the list are:")
print(l[0:3])
print("Three items from the middle of the list are:")
print(l[4:7])
print("The last three items in the list are:")
print(l[-3:])

INPUT
null

OUTPUT
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]

4-13 自助餐

  题目描述:在一家自助餐馆中,只提供五种简单的食品。请想出五种简单的食物,并将其存储在一个
元组中。
  ·使用一个for循环将该餐馆提供的五种食品都打印出来。
  ·尝试修改其中的一个元素
  ·餐馆调整了菜单,替换了其中两种食品。请编写这样一个代码块:给元组变量赋值,并使用
    一个for循环将新元组的每个元素都打印出来。

代码展示:

foods = ('yukkuri', 'mushroom', 'Mystia', 'dango', 'usaginabe')
for food in foods:
    print(food)

# foods[0] = 'whatever'
# Type error: 'tuple' object does not support item assignment

foods = ('yukkuri', 'hakkerou', 'Mystia', 'bread', 'usaginabe')
for food in foods:
    print(food)

INPUT
null

OUTPUT
yukkuri
mushroom
Mystia
dango
usaginabe
yukkuri
hakkerou
Mystia
bread
usaginabe

猜你喜欢

转载自blog.csdn.net/akago9/article/details/79589967