cycle
1 concept
Generalized: the case of a phenomenon or recurring cycle, this state is referred to as loop
Narrow: In the condition is met, repeatedly executes a piece of code, with which this occurs in a programming language called round. This code is repeatedly performed is referred to as loop
When repeatedly execute a piece of code, you need at the right time will cycle stopped, or will cause an infinite loop
Python loop provided: while statement, for-in statement
2 Use
2.1 while syntax
while 表达式:
循环体
How it works: When encountered while statement, first calculate the value of the expression, if the expression is false, then skip the entire while statement, continue with the following code; if the expression evaluates to true, the loop body is executed
# 计算1-100的和
sum1 = 0
i = 1
while i <= 100:
sum1 += i
i += 1
print(sum1,i)
2.2 while-else
while 表达式:
循环体
else:
【else语句块】
i = 0
while i < 100:
print("hello world")
if i > 50:
break
i += 1
else:
print("循环正常结束")
Description: When the statement is executed while, run [] else block, break out of loop else if not performed
2.3 infinite loop
In the loop, the expression is always true cycle
while True:
#循环体
while 1:
#循环体
Nesting 2.4 while statement
while 条件1: #外层循环
【语句块A】
while 条件2: #内存循环
【语句B】
Execution process: First, the outer loop determines a condition, if true, executing the statement block [A] in the loop, the inner loop execution, the determination condition 2 is satisfied, if true, execute the inner loop statement block [ B], after performing the inner loop, the outer loop condition is determined again ....
- Features: take a step outer loop, the inner loop is executed again
- Outer loop and inner loop of the loop variable must be different
- The heavy cycle must be fully nested inside the outer heavy cycle
Demo: Print multiplication tables
#行数
i = 1
while i <= 9:
# 打印每行的内容
j = 1 # 内循环必须完全嵌入到外重循环里
while j <= 9:
print("%d * %d = %2d "%(i,j,i*j),end='')
j += 1
print()
i += 1