一、循环简介
1.循环作用
让代码更⾼效的重复执行。
2.循环的分类
在Python中,循环分为while 和for 两种,最终实现效果相同。
二. while的语法
1.输出5次hello world
i
= 1
while i
<=5:
print('hello world')
i
+=1
三. while的应用
1.应用一:计算1-100累加和
i
= 1
result
= 0
while i
<= 100:
result
+= i
i
+= 1
print(result
)
2 应用二:计算1-100偶数累加和
i
= 1
result
= 0
while i
<= 100:
if i
% 2 == 0:
result
+= i
i
+= 1
print(result
)
i
= 0
result
= 0
while i
<= 100:
result
+= i
i
+= 2
print(result
)
四、break和continue
break:终止此循环
i
= 1
while i
<= 5:
if i
== 4:
print(f
'吃饱了不不吃了')
break
print(f
'吃了第{i}个苹果')
i
+= 1
continue:退出当前一次循环继而执行下一次循环代码
i
= 1
while i
<= 5:
if i
== 3:
print(f
'大⾍⼦,第{i}个不吃了')
i
+= 1
continue
print(f
'吃了第{i}个苹果')
i
+= 1
五、while循环嵌套
1.语法
六、while循环嵌套应用
1.打印星号(三角形)
j
= 0
while j
<= 4:
i
= 0
while i
<= j
:
print('*', end
='')
i
+= 1
print()
j
+= 1
2.九九乘法表
j
= 1
while j
<= 9:
i
= 1
while i
<= j
:
print(f
'{i}*{j}={j*i}', end
='\t')
i
+= 1
print()
j
+= 1
七、for循环
1.语法
str1
= 'hello'
for i
in str1
:
print(i
)
2.break
str1
= 'hello'
for i
in str1
:
if i
== 'e':
print('遇到e不打印')
break
print(i
)
3.continue
str1
= 'hello'
for i
in str1
:
if i
== 'e':
print('遇到e不打印')
continue
print(i
)
八、while…else
1.语法
i
= 1
while i
<5:
print('hello world')
i
+=1
else:
print('hello python')
2.break
i
= 1
while i
<5:
if i
==3:
print('hello')
i
+=1
break
print('hello world')
i
+=1
else:
print('hello python')
3.continue
i
= 1
while i
<5:
if i
==3:
print('hello')
i
+=1
continue
print('hello world')
i
+=1
else:
print('hello python')
九、for…else
1.语法
str1
= 'hello'
for i
in str1
:
print(i
)
else:
print('循环正常结束之后执行的代码')
2.break
str1
= 'hello'
for i
in str1
:
if i
== 'e':
print('遇到e不打印')
break
print(i
)
else:
print('循环正常结束之后执行的代码')
3.continue
str1
= 'hello'
for i
in str1
:
if i
== 'e':
print('遇到e不打印')
continue
print(i
)
else:
print('循环正常结束之后执行的代码')
转载请注明原文地址: https://win8.8miu.com/read-4265.html