Python for 循环
- Python条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块
Python for 循环
- 可迭代对象可以是字符串,列表,元组,字典,集合,range对象等。
- 将in后面可迭代对象的元素依次赋值给前面的变量,每赋值一次,执行一次语句块,也就是一次循环。
for 变量名[,变量名2,变量名3...] in 可迭代对象
循环语句
Python for 循环常用搭配
- range()函数
- dict.items, dict.keys, dict.values
- enumerate(sequence, [start=0])
index循环
animals = ['dolphin', 'hippo', 'crocodile']
for idx_animals in range(len(animals)):
print('index: %d, the animal: %s'
% (idx_animals, animals[idx_animals]))
result:
index: 0, the animal: dolphin
index: 1, the animal: hippo
index: 2, the animal: crocodile
for循环字典的遍历
dict1=dict(name="ZhouYing", age=18)
for key, value in dict1.items():
print("key:{0}, value:{1}".format(key, value))
for key in dict1.keys():
print("key:{0}, value:{1}".format(key, dict1[key]))
for value in dict1.values():
print("value: %s" % value)
result:
key:name, value:ZhouYing
key:age, value:18
key:name, value:ZhouYing
key:age, value:18
value: ZhouYing
value: 18
for循环配合enumerate 函数
enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
birds = ["sparrow", "swallow", "woodpecker", "nightingale"]
for idx, bird_name in enumerate(birds):
print(idx, bird_name)
result:
0 sparrow
1 swallow
2 woodpecker
3 nightingale
Python for 循环语句的跳出
for+break
- 同while循环一样,只要运行到break就会立刻中止本层for循环
num = 5
for i_num in range(num):
print("loop cycle: %d" % i_num)
if(i_num==2):
print("break, jump out of the loop")
break
else:
print("The loop ends normally")
result:
loop cycle: 0
loop cycle: 1
loop cycle: 2
break, jump out of the loop
for+continue
- 同while循环一样,只要运行到continue就会立刻中止本层for循环的本次操作,接着回到for循环的下一次循环语句。
num = 5
for i_num in range(num):
print("loop cycle: %d" % i_num)
if(i_num==2):
print("skip this loop cycle")
continue
else:
print("The loop ends normally")
result:
loop cycle: 0
loop cycle: 1
loop cycle: 2
skip this loop cycle
loop cycle: 3
loop cycle: 4
The loop ends normally
for+else
- 当迭代对象完成所有迭代后且此时的迭代对象为空时,则执行else子句;如果迭代对象因为某种原因(如带有break关键字)提前退出迭代,则else子句不会被执行,程序将会直接跳过else子句继续执行后续代码(当乖乖执行完for的所有语句,奖励一个else)
num = 5
for i_num in range(num):
print("loop cycle: %d" % i_num)
else:
print("The loop ends normally")
result:
loop cycle: 0
loop cycle: 1
loop cycle: 2
loop cycle: 3
loop cycle: 4
The loop ends normally
for循环与while循环的异同
- 都是循环,for循环可以干的事,while循环也可以干。
- while循环是条件循环,循环次数取决于条件何时变为假。
- for循环是取值循环,循环次数取决in后包含的值的个数。
- for主要应用在遍历中, 而while循环很少进行遍历使用(语句过多,没有for方便),while主要用于判断符合条件下循环。
- while循环通常有条件判断,变量值自增等操作,在使用中需要比较for和while的执行时间和效率。