>>> for value in range(1,7):
print(value)
1
2
3
4
5
6
使用list()函数将range()的结果直接转换为列表
>>> numbers = list(range(1,6))
>>> print(numbers)
[1, 2, 3, 4, 5]
>>>
squares = [54,987,3345]
for value in range(1,11):
square = value**2 ##计算当前值得平方,并将结果存储到square中
squares.append(square) ##将新得到的结果,附加到列表square末尾
print(squares)
[54, 987, 3345, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>>
让代码更加简洁,可以不使用临时变量square
squares = [54,987,3345]
for value in range(1,11):
squares.append(value**2)
print(squares)
[54, 987, 3345, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>>
>>> digits = [232,786,232555,87654,987,1234,765]
>>> min(digits)
232
>>> max(digits)
232555
>>> sum(digits)
324213
>>>
>>> squares = [value**2 for value in range(1,11)]
>>> print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>>
>>> for n in range(1,21):
print(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
>>> n =list(range(1,100001))
>>> min(n)
1
>>> max(n)
100000
>>> sum(n)
5000050000
>>>
range(start, stop[, step])
range 构造器的参数必须为整数(可以是内置的 int 或任何实现了 index 特殊方法的对象)。 如果省略 step 参数,其默认值为 1。 如果省略 start 参数,其默认值为 0,如果 step 为零则会引发 ValueError。
Odd_numbers = list(range(1,21,2))
print(Odd_numbers)
for Odd_number in Odd_numbers:
print(Odd_number)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
1
3
5
7
9
11
13
15
17
19
>>>
for Multiple_of_three in range(3,31,3):
print(Multiple_of_three)
3
6
9
12
15
18
21
24
27
30
>>>
Cube_of_three = []
for number in range(1,11):
Cube_of_three1 = number**3
Cube_of_three.append(Cube_of_three1)
print(Cube_of_three1)
1
8
27
64
125
216
343
512
729
1000
>>>
Cube_of_three = [number**3 for number in range(1,11)]
for n in Cube_of_three:
print(n)
1
8
27
64
125
216
343
512
729
1000
>>>