1. for i in range() 循环:
for 循环: 已知循环次数的情况下, 需要多次重复代码块时使用
while 循环: 终止条件决定何时停止
range 控制循环次数,range(start,stop, step)
for i in range(6): -- stop = 6
print(i) --- 0,1,2,3,4,5
for i in range(20, 25):
print(i) -- 20,21,22,23,24
for i in range(50, 0, -10):
print(i) -- 50, 40, 30, 20, 10
作为循环固定次用法:
for i in range(3):
sum += number
return sum
2. range(len()) 用在list (is better expressed with enumerate)
list = ['a', 'b', 'c']
for i in list:
print(i) ---- a b c
等同于
list = ['a', 'b', 'c']
for i in range(len(list)):
print(list[i]) ---- a b c
this is useful when you want to modify the list at certain positions
i.e.
list = ['a', 'b', 'c', 'd', 'e']
for i in range(len(list)):
if list[i] in 'aeiou':
list[i] = 'vowel'
else:
list[i] = 'consonant'
list == ['vowel' 'consonant', 'consonant', 'consonant', 'vowel']
for i in range() iterates through numbers. For element in list iterates through whatever is in the list. for i in range(len(list)) iterates through numbers which can be used for index access of list.
3. for in list 循环
words = ['a', 'b', 'c']
for i in words:
print(i) -- a b c
列表和其它的“序列”数据类型 比如 strings以及tuples(元组)都常常被用于循环,因为他们有“可被迭代”的特性。你可以组合这些数据结构与range()
协同,去在列表中增加项目
for i in range(len(words)):
words.append('d')
print(words)---a,b,c,d,d,d
此处将'd'
作为占位字符串,在words
列表中增加了len(words)次'd'
(len(words)为起始时words
列表中项目的总数/列表原长)
用for
循环构建一个列表:
list = []
for i in range(3):
list.append(i)
print(list) - []