一、for循环举例
复制以下代码运行,即可理解代码。
str1 = 'python'
for i in str1:
if i == 'n':
print(i, end='')
else:
print(i)
print()
print('----------------') # 区分上下部分
for i in str1:
if i == 'h':
print('遇见h, 结束整个循环且没有打印h')
break
print(i)
print('----------------') # 区分上下部分
for i in str1:
if i == 'h':
print('遇见h, 结束这次循环, 即不打印h')
continue
print(i)
二、while循环
# basic cycle
i = 0
while i < 5:
print("dear, I'm sorry")
i += 1
print('forgive you only this time')
# summation
i = 1
s = 0
while i <= 100:
s += i
i += 1
print(s)
# summation -- while and if
i = 1
s = 0
while i <= 100:
if i % 2 == 0:
s += i
i += 1
print(s)
三、while嵌套循环
i = j = 0
while i < 5:
j = 0
while j < 5:
print('*', end='') # at the end of 'print()', the default is '\n'
j += 1
print() # when a row go to end, we need to enter
i += 1
i = j = 0
while i < 5:
j = 0
while j <= i:
print('*', end='') # at the end of 'print()', the default is '\n'
j += 1
print() # when a row go to end, we need to enter
i += 1
四、while嵌套循环打印9x9乘法表
i = j = 1
while i <= 9:
# 一行表达式开始
j = 1
while j <= i:
print(f'{j} * {i} = {i*j}', end='\t')
j += 1
# 一行表达式结束
print()
i += 1
五、break和continue语句
# the usages of break
i = 1
while i <= 5:
if i == 4:
print('I was full')
break
print(f'{i} apples had been ate')
i += 1
print(end='\n') # enter,looks clearly
# the usages of continue
i = 1
while i <= 5:
if i == 3:
print('I have eaten a big worm,this apple will not be eaten')
i += 1
continue # this "continue" is not necessary
print(f'{i} apples had been ate')
i += 1
print(end='\n') # enter,looks clearly
# another method
i = 1
while i <= 5:
if i != 3:
print(f'{i} apples had been ate')
i += 1
else:
print('I have eaten a big worm,this apple will not be eaten')
i += 1
print(end='\n') # enter,looks clearly
# another method
i = 1
while i <= 5:
if i == 3:
print('I have eaten a big worm,this apple will not be eaten')
i += 1
# this "continue" is not necessary
print(f'{i} apples had been ate')
i += 1