PYTHON教程之循环语句while和for循环
#1.for循环
#for item in sequence:
# expressions
#sequence 为可迭代的对象,item 为序列中的每个对象
example_list = [1,2,3,4,5,6,7,12,543,876,12,3,2,5]
example_list = [1,2,3,4,5,6,7,12,543,876,12,3,2,5]
for i in example_list:
print(i)
print('inner of for')
print('outer of for')
#2.while循环
#while condition:
# expressions
#其中 condition 为判断条件,在 Python 中就是 True 和 False 其中的一个,如果为 True
# 那么将执行 exexpressions 语句,否则将跳过该 while 语句块接着往下执行。
condition = 0
while condition < 10:
print(condition)
condition = condition + 1
#输出的结果将是 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 第一行设置 condition 的 初始值为 0,
# 在进行 while 判断的时候 0 < 10 为 True, 将会执行 while 内部 的代码,首先先打印出该值,
# 然后将 condition 值加 1,至此将完成一次循环;再 condition 的值与 10 进行比较,仍然为 True,
# 重复如上过程,至到 condiiton 等于 10 后,不满足 condition < 10 的条件(False),
# 将不执行 while 内部的内容 所以 10 不会被打印。
#3.break退出整个循环
#break用法,在循环语句中,使用 break, 当符合跳出条件时,会直接结束循环,这是 break 和 True False 的区别。
while True:
b= input('type somesthing:')
if b=='1':
break
else:
pass
print('still in while')
print ('finish run')
#continue退出本次循环
while True:
b=input('input somesthing:')
if b=='1':
continue
elif b=='9':
break
else:
pass
print('still in while' )
print ('finish run')
#在代码中,满足b=1的条件时,因为使用了 continue , python 不会执行 else 后面的代码,而会直接进入下一次循环。
运行结果:
"D:\Program Files\python\python.exe" "D:/Program Files/python/example/PYTHON教程之循环语句while和for循环.py" 1 inner of for 2 inner of for 3 inner of for 4 inner of for 5 inner of for 6 inner of for 7 inner of for 12 inner of for 543 inner of for 876 inner of for 12 inner of for 3 inner of for 2 inner of for 5 inner of for outer of for 0 1 2 3 4 5 6 7 8 9 type somesthing:2 still in while type somesthing:2 still in while type somesthing:1 finish run input somesthing:1 input somesthing:1 input somesthing:2 still in while input somesthing:2 still in while input somesthing:9 finish run Process finished with exit code 0


评论