当前位置:首页>基础编程学习>Python>Python for循环
Python for循环
阅读 4
2024-09-14

for循环

while循环一样,for可以完成循环的功能。
Pythonfor循环可以遍历任何序列的项目,如一个列表或者一个字符串等。

普通的循环示例如下:

name = 'Python Apple China'
for x in name: 
	print('----')
	print(x)


带有break的循环示例如下:

name = 'Python Apple China'
for x in name: 
	print('----')
	if x == 'A':
		break
         print(x)


小总结:
break的作用:用来结束整个循环

continue

带有continue的循环示例如下:
name = 'Python Apple China'
for x in name: 
	print('----')
	if x == 'A':
		continue
	print(x)	


小总结:

continue的作用:用来结束本次循环,紧接着执行下一次的循环

3. 注意点

break/continue只能用在循环中,除此以外不能单独使用
break/continue在嵌套循环中,只对最近的一层循环起作用

for循环的格式1

for 临时变量 in 列表或者字符串等:
循环满足条件时执行的代码
name = 'Python Apple China'
for x in name: 
	print(x)	

for循环的格式2

for 临时变量 in 列表或者字符串等:
循环满足条件时执行的代码
else:
循环不满足条件时执行的代码
name = ''
for x in name: 
	print(x)
else:
	print("没有数据")	
运行结果如下:


评论 (0)