Python base 4: Analyzing the circulation

IV. Control flow (decision and loops)

Flow control is an important part of the program, especially in the very important process-oriented programming. Similar flow control various programming languages, python flow control is very simple, just look at the rest of the programming foundation of two grammar can be.

4.1 if ... elif ... else ... conditional statements

Conditional statement is used to control the program, just like the intersection, take a different path to the program under different conditions. Conditional statement that makes the program with core human-like "judgment" capability.

  • Conditional statement used ifto indicate the determination condition, with subsequent :block of statements connected indentation behavior under the specified conditions.
  • elseAnd the statement is ifcorresponding to the current plane ifwhen not occur else statement block contents
  • elifThe above condition is not established, the subsequent execution condition satisfied later block. Equivalentelse if
  • Analyzing the support block of statements statements nested loop or is a multilayer determined. Note indentation.
### if  elif  else
if condition1:
    statement1
elif condition2:
    statement2
else:
    statement3
    
### 嵌套  
if condition1:
    statement1
    if condition2:
        statement2
    else:
        statement3
else:
    statement4
  • If you can write a single line is simple: if condition: statement
  • there is no python case, switcha select statement like, can ifbe accomplished.

Conditional expression

The conditional expression is the result of the expression, for example, conditional assignment:

# if语句
if a<b:
    minvalue=a
else:
    minvalue=b

# 条件表达式    
minvalue=a if a<b else b

Used in the list of conditional expression which formula is derived:

There are two forms:

  • Assignment In front, ifat forthe back, with no elsebranches, only play a role in defining the filter conditions. Conditions multilayer support.
  • With a elseform of expression and general conditions, as written on the forfront.
[ x*x for x in range(10) if x%2==0 ]
## [0, 4, 16, 36, 64]
[ x*x for x in range(10) if x%2==0 if x>5 ]
## [36, 64]
[ x*x if  x%2==0 else x**3 for x in range(10) ]
## [0, 1, 4, 27, 16, 125, 36, 343, 64, 729]

4.2 for loop

Programming in circulation is extremely common and important part of the operation can be carried out by repeating the cycle, helping people get away from the tedious work. Python support forcirculation and whilecirculation, as no other language goto, dosuch as recycling.

Cycling conditions were part of determining whether to continue execution of the cycle, whether or while loop has for this part. Loop that is a member for checking inthe condition when the loop variable within the scope of, the structural portion of the cycle continues.

For cycling conditions:

  • inFront loop variable, as the cycle changes automatically, every time the latter may be the actual object called iterative next()method, resulting in a change of the loop variable.
  • inBehind the object generally is iterative, such as a list, array, dictionary (iteration Key), file objects, etc. to use digital control, generally using range()column number function for producing recycled.
  • forIs a limited circulation cycle, in accordance with the content of loop iterations performed the object; This whilerecycling loop control of different specified condition, the condition has been true for the cycle, it may be an infinite loop, when the loop may be performed for previously unknown number of cycles, did not stop until certain conditions
  • Loop variable is actually every time cycle are executed once i=iterobj.next(), and its value is determined by the output iterator, the iterator produced before the cycle note that there are several items:
    • Not change the loop variable inside the loop, because each loop will be re-assigned to the loop variable. It must and C ++, change the loop variable which changes will be affected.
    • Despite the iterations of the loop generated at the beginning of the cycle, but if iterables cycle of change, will affect the circulation, because the iterator remembers iteration of that run to iterables what position, but changing iterables content, it will affect circulation.
    • The scope of the loop variable inside the loop is not private, but also before the loop if it is defined, it will value of the loop variable after the end of the cycle retains the last value of the loop redefined based on value of the loop variable is also often used in nest the inner loop.
    • loop variable assignment for the support of unpack operations, such as for x,y in dictA.items()that at the same time several variable assignment, but pay attention to the structure within the object to be iterative to unpack consistent.
  • forAlso supports circulation else:clause is a condition is not met then perform an action out of the loop when the note. elseIn the cycle when the execution condition is not satisfied, it will perform a complete cycle when there is a general exception: use breakwhen out of the loop, and no Analyzing then cycling conditions, and therefore does not elseclause.

In the sequence of for intime, try not to be deleted by, sorting and other operations on the sequence, error-prone (may interfere with iterators)! Best to use an alternative sequence seq2=seq1[:]for the assignment operation. Note that examples of the latter.

For looping content:

  • Cycle will be forthe :statement immediately blocks, each block of the statement is executed later
  • It supports nested loop statement block, i.e., the inner loop then nested loop, nested loops executed, is equivalent to a layer of one execution cycle.
  • Loop support block break, continuestatements, control loop:
    • breakIs out of the loop, where the attention is out of the current loop block, is not out of the loop superiors. Skips for the elseclause.
    • continueSkipping back part of the block of statements, the implementation of the next cycle. That cycle interrupt the current execution cycle
# for 循环一般形式
for i in iterableObj:
    statement;

# 可迭代对象例如: list/tuple/set/string
for i in iterobj:
##### 判断是否可迭代对象:
from collections import Iterable
isinstance(obj, Iterable);

# 嵌套循环(可嵌套for或while循环): 
for i in range(1,100,10):
    ## 1 11 21 ... 91
    for j in range(10):
        ## 0 1 2 ... 9
        print i+j
## 1 2 3 ... 100

# 使用else子句, 注意break的情况
for i in range(1,100,input("Enter an Interval:\n")):
    if i % 17 == 0: 
        print "Number",i," found! Break!"
        break
else:
    print "Can't find number!"
## 输入3: Number 34  found! Break!
## 输入13: Can't find number!

# for循环变量不被循环过程所改变
for i in range(10):
    i+=2
    print i
## 2 3 ... 10 11

# 改变可迭代对象会影响循环:
k=range(10)
j=0
for i in k:
    k[j+1]=k[j+1]**2
    k.append(k[j+1])
    j+=1
    print i
## 0 1 4 9 16 25 36 49 64 81 1 16 81 256 625 1296 2401 4096 6561 1 256 6561 ...
### 在该循环中, 既改变了迭代对象列表k的每项的值, 同时还不停增长k的长度, 因此该循环导致死循环.


# 使用创建的数列来控制循环
for i in range(start, end, step):

# 经常会使用计数来记录循环运行次数或作索引
n=0
for i in range(1,100,3):
   print "Index %d is %d;" % (n,i),
   n+=1 
## Index 0 is 1; Index 1 is 4; ... Index 31 is 94; Index 32 is 97;

# 对于列表, 循环数值同时亦可以记录对应索引值,可以使用 enumerate函数 (会进行解包)
### 上述例子可以改为: 
for index, value in enumerate(range(1,100,3)):
    print "Index %d is %d;" % (index,value),

# 利用zip来合并序列的项, 并解包
for x, y in zip([1,2,3,4],'hello'):
    print y,x,
## h 1 e 2 l 3 l 4
    
# 对于字典, 循环控制比较特殊
### 循环字典的键: 
for key in dict:
### 循环字典的值
for val in dict.values():
### 同时循环字典的键和值 
for key,val in dict.items():

# 可以对于文件对象, 逐行读出文件内容:
f=open('filename')
for line in f:
    print line

Correlation function learning

In addition to the above-mentioned data structure range, xrange, reversed, sortedfor generating a list or iterator, these can be used for the object may be iterative, in addition, there is the following related:

  • enumerate(iterable [, start=0]): Generating an iteration of enumeratethe object,
    the object may individually generate tuples (0, seq [0]) , (1, seq [1]) .... iteration to the object and its index number, the index number is the default start 0, you can define your own.
  • zip(seq1, [seq2 ,seq3 ....]): Given the same index entry sequence combined into tuples, the combined index of the tuple is returned as a list of all the length of the sequence if not, a short length of the sequence, whichever note python2 the method may return a waste of memory the big list, but it is python3 iterator. python2 can be used itertools.izip()to return an iterator.

4.3 while loop

whileCirculation loop is custom criteria, format while 条件: 语句块, as long as conditions return True, a block of statements is executed later.

  • Because the while loop can be defined cycling conditions, the loop can be under the circumstances, in order to achieve indeterminate number of cycles, or even been circulated.
  • Support for nested loops, for/ whileall kinds of nesting.
  • Support breakand continueuse
  • while also supports the elseclause (executed once when the loop condition is not met), breakwithout the else clause
  • while True: breakIs also commonly used, the conditions would have been directly True cycle, the cycle is interrupted by the use of the block of statements breakto achieve, in combination generally ifused.
while condition:
    statement;
[else:]
    [statement;]
    
while True:
    statement1
    
    if condition:
        statement2
        break

In other languages there, as well as cycling do until/whileand gotostatements can be used for circulation, but does not support python can use whileloop to achieve ( gotorather special, because the general avoid the use of error-prone)

4.4 break, continue, exit

These three terms (exit is a function of) the main control loop execution is out of the loop or skip the subsequent, generally used in conjunction with conditional statement, and under certain circumstances.

  • break: Interrupt the whole loop and jump is not executed. elseClause.
  • continue: Skip the next part of the cycle, the beginning of the next cycle.
  • exit() : The end of the script, and then when an error occurs.

There is also a separate statement a word:

  • pass : This statement is empty, nothing is executed, purely in order to meet the requirements without syntax errors exist in the empty statement, sometimes as a temporary placeholder until the subsequent re-add the appropriate code.

Reproduced in: https: //www.jianshu.com/p/91a003ee445c

Guess you like

Origin blog.csdn.net/weixin_33905756/article/details/91237762