table of Contents
for loop
Loop: Repeat one kind of thing
Ten digital printing, directly if print
required for printing one by one, using the loop for only two lines of code:
#打印十个数字
for i in range(10):
print (i)
The result:
0
1
2
3
4
5
6
7
8
9
Process finished with exit code 0
- break: break the cycle ahead
When you need to break the cycle, you can press the following manner:
# break :中断循环
for i in range(10):
if i == 3:
break
print(i)
The result:
0
1
2
Process finished with exit code 0
- continue: out of this cycle, the following operation is not performed, directly into the next cycle
Implementation:
# continue :跳出本次循环,不执行下面代码,进行下一次循环
for i in range(10):
if i == 3: #当i=3时,不打印,继续打印后面的数字
continue
print(i)
The result:
0
1
2
4
5
6
7
8
9
Process finished with exit code 0
- for nested loop:
Print calendars, implementation code:
#打印日期
for j in range(1,13):
for i in range(1,32):
print(f'{j}月{i}日')
#保存为文本文档
with open('打印日期1.txt','a',encoding= 'utf-8') as f:
data = f.write(f'{j}月{i}日')
print('打印完毕')
Generated Files: Print Date 1.zip
- for nesting and if
The results of the above piece of code may know, each month is 31 days, is clearly unreasonable, and content together, affect the reading, the following use nested for loops and if judged to be printed on the normal date, and simple adjust its format.
Implementation code:
#打印日期
for j in range(1,13):
for i in range(1,32):
if j == 2 and i>28:
continue
elif j in[4, 6, 9, 11]and i >30:
break
print(f'{j}月{i}日')
#保存为文本文档
with open('打印日期2.txt','a',encoding= 'utf-8') as f:
data = f.write(f'{j}月{i}日' + '\n') #增加txt内的换行符
print('打印完毕')
Generated Files: Print Date 2.zip