Program loop structure

Traversal cycle

Run traverse a loop structure is formed
for <loop variable> in <traverse Structure>:
<statement block>
individually extracted from the element to traverse the structure, in the variable loop, each loop element into the loop variable is obtained, and execute a block of statements

Counting loop

for i in range<次数>):
     print" "

eg:
for i range(5)
print(i)
eg
for i range(5)
print"hello:",i)

for i in range(M, N, K):
    print(i)

输出  ...:     
1
2
3
4
5

Specific cycles

for i in range(1, 6, 2):#表示1。。。5 跨度为2
  ...:   print(i)
  ...:   
1
3
5

String traversal cycle

C in S for:
<statement block>
S is a string, each character string traversed, generation cycle

A list of cycle

Item in LS for:
<statement block>

       for item in [123, "py", 465]:
  ...:     print(item, end=",")
  ...:     
123,py,465,

Loop through files

Line in Fi for:
<statement block>
Fi is a file identifier, which traversing each row, generation cycle.
eg:

for line in fi:     
print(line)

Infinite loop

A circulation operation controlled conditions:
the while <Condition>:
<statement block>
is repeatedly executed statement block, until the end condition is not satisfied

In[8]: a=3
while a > 0:
  ...:     a = a - 1
  ...:     print(a)
  ...:     
2
1
0
In[8]: a=3
while a > 0:
  ...:     a = a + 1
  ...:     print(a)
  ...:    无限循环点ctrl+c退出

Loop control of reserved words

break and continue to retain control word
break out of the cycle and end the current entire statement after the execution cycle
continue when the end of the cycle, continue to perform the subsequent cycles

for c in "PYTHON": #字符串循环
   ...:     if c == "T": #表示不打印T遍历其他字符串
   ...:         continue
   ...:     print(c, end="")
   ...:     
PYHON
In[15]: for c in "PYTHON": #遇上保留字不循环其他
   ...:     if c == "T":
   ...:         break
   ...:     print(c, end="")
    PY
In[16]: s = "PYTHON"
while s !="":  #判断s是否是空字符串
   ...:     for c in s: 
   ...:         print(c, end="")
   ...:     s = s[:-1] #每次去掉一个字符
   ...:     
PYTHONPYTHOPYTHPYTPYP
In[18]: s = "PYTHON"
while s !="":
   ...:     for c in s:
   ...:         if c == "T": #跳出当次循环
   ...:            break     #一个break只能跳出一次循环
   ...:         print(c, end="")
   ...:     s = s[:-1]
   ...:     
PYPYPYPYPYP

Advanced usage cycle

Circulation and else
when the cycle is not quit when the break statement, the else statement block, else block as a "normal" to complete the cycle of reward, else similar usage and exception handling

In[20]: for c in "PYTHON":
   ...:     if c == "T":
   ...:         continue
   ...:         print(c, end="")
   ...:     else:
   ...:         print("正常退出")
   ...:         
PYHON正常退出

break语句
for c in "PYTHON":
   ...:     if c == "T":
   ...:        break
   ...:     print(c, end="")
   ...: else:
   ...:     print("正常退出")
   ...:     
PY


在这里插入代码片
Published 11 original articles · won praise 0 · Views 75

Guess you like

Origin blog.csdn.net/kyra1997/article/details/105121938