python中while循环和for循环的定义和详细的使用方法

Python中循环的定义

反复做某事,具有明确的开始和结束。

在Python中循环有whilefor两种方式

while循环

"""
while 条件:
	需要循环的语句
"""

i = 0
while i<3:
  print(i)
  i+=1

# 输出结果:
"""
0
1
2
"""

for循环

# range(2)是一个迭代器对象,所以for i in 可迭代对象(可以是列表list,字典dict等等)
for i in range(2):
  print(i)
  
# 输出结果:
"""
0
1
""" 

循环的终止和退出

break 结束当前循环

while True:
  print("hello!")
  break  # 死循环会在break结束循环

continue 结束本次循环,继续执行代码

for i in range(2):
  if i == 1:
    continue
  print(i)

# 输出结果:
"""
0
"""  

在continue之后的代码不会被执行,重新进入下一次循环

posted @ 2018-09-19 18:40  FANDX  阅读(6820)  评论(0编辑  收藏  举报