Python3 Process Control Statements
Python3 's Process Control statements include:
- If condition statement
- While Loop statement
- For Loop statement
- Range function
- Break
- Continue
- Pass
One, if statement
The IF statement is the most commonly used conditional control statement in Python in the form of:
if 条件一: statementselse: statementsif 条件一: statementselif 条件二: statementselse: statements
Attention:
1. Use a colon (:) after each condition to indicate the next statement block to be executed after the condition is met
2, using indentation to divide the statement block, the same indentation number of statements together to form a statement block
3. There are no switch–case statements in Python
code example:
# 示例1:a = 7if a > 4: print(‘ok‘)else: print(‘no‘)# 示例2:a = 7if a < 4: print(‘小于4‘)elif a < 8: print(‘4<a<8‘)else: print(‘a>8‘)
Second, while Loop statement
The format of the while statement is:
while 条件: statements
Also note the colon and indentation, when using the while loop, pay attention to the control of the loop, not necessary, do not write a dead loop, in addition, there is no do in Python: While loop
Example code:
# 先会刹车a = 4i = 0while i < a: print(i) i += 1 # 此处控制循环达到边界条件
Third, for loop statements
The FOR Loop statement in Python can iterate through any sequence and iterate in the order in which the elements appear in the sequence, in the general format:
for variable in sequence: statements else: statements
Example code:
for x in [1,2,3]: # 列表 print(x)
Four, Range function
The function range () is commonly used in a for loop to produce a desired arithmetic sequence:
for x in range(5): # 随机数 print(x)01234
V. Break, continue, pass, and ELSE clauses
- Break jumps out of the loop
- Continue jump out of this cycle and into the next round cycle
- Pass indicates that nothing is done, it only requires a statement in syntax but the program does not need any action when it is used. The pass statement is designed to maintain the integrity of the program structure.
- You can also use the ELSE clause in a loop statement, which executes when the sequence traversal ends (for statement) or the loop condition is false (while statement), but does not execute when the loop is terminated by break
Example code:
# 示例1:for x in [1,2,3]: if x == 3: break # 用if控制 x == 3 则退出循环,下面的语句也不执行。 print(x)else: print(‘end‘)12# 示例2:for x in [1,2,3,4,5]: if x == 2: continue # 退出本次循环,进入下一层循环 print(x)1345# 示例3:for x in [1,2,3]: #循环完所有元素才执行else print(x)else: print(‘end‘)123end
Python3 Process Control Statements