Cyclic structure of the program
Traversal cycle
Format :
for 循环变量 in 遍历结构 :
语句块
- It can be extracted one by one from the traversing element into the loop variable in the structure
- Traversing the structure contains many types
- Each cycle element is obtained from a structure placed traversing the loop variable, and perform a block.
Application :
- Count cycle (N times): a traversing
range(N)
orrange(M,N,K)
number sequence generation, resulting in circulation.
for i in range(N):
语句块
- String traversal cycle
for c in s :
语句块
- Where s is a string, c representative of each character in the string.
- Removed from the string sequentially into each character c in circulation.
Examples :
- List traversal cycle
for item in ls :
语句块
+ -ls是一个列表,遍历列表的每一个元素,产生循环
- File traversal cycle
for line in fi :
语句块
+ -fi是一个文件标识符,遍历这个文件的每行,产生循环
+ 文件标识符相当于用一个变量来标识系统中的一个文件
Infinite loop
- Infinite loop circulation operation is controlled by the conditions
while 条件 :
语句块
- When the program runs can not be stopped, you can ctrl + c to exit the run
Like reserved words break the cycle and continue to control the usage and C language
Cycle and else
for 循环变量 in 遍历结构 :
语句块1
else :
语句块2
或者
while 条件 :
语句块1
else :
语句块2
- When the cycle is not exit the break statement, the else block of statements
- else block cycle can be completed as a normal reward
example: