07python program control flow

07python program control flow

Basic structure of the program

The program generally consists of three parts: sequence structure, branch structure, and loop structure.

Branch structure

Single branch structure: if statement

if 条件 :
	语句块

A statement block is a sequence of one or more statements executed after the if condition is met. The statement in the statement block expresses the containment relationship by forming an indentation with the line where the if is located .

Two branch structure

if 条件 :
	语句块1
else:
	语句块2
  • Concise expression of half structure:
<表达式1>if <条件> else <表达式2>	

The function is the same as above

Multi-branch structure

if 条件1 :
	语句块1
elif 条件2:
	语句块2
...
else:
	<语句块n>

The last else statement can be omitted.

Cyclic structure

for

Python can use the for statement to loop through the entire sequence of values.

for <var> in <sequence>:
	语句块

During the execution of the for loop, it traverses the sequence directly. Instead of generating a new copy of the sequence in memory for traversal.
for loop. Very suitable for traversing container objects . That is, list tuple dictionary collection strings and similar objects such as map and tip.

for 循环遍历 in 容器类对象:
	语句块
else:
	else代码语句块

When the loop condition is not established, the else statement block is executed.
The range() function can create a list of integers and loop with for

for common methods

for i in range(10) Execute 10 count loops
String loop: for c in s
list traversal: for item in L
file traversal loop: for line in fi:
fi is a file identifier, traverse each line of it, Generate loop

while

while 条件表达式:
	循环体
else:
	else代码语句块

When the condition is not established, execute the else statement block.
Note that in for else or while else, you must ensure that the for and while loops exit normally before executing the else statement, and for and while are not exited by break

break continue

The usage of Break is similar to C language. Used to jump out of the innermost loop.
continue ends the current loop and continues to solve the loop conditions.
continue just ends the loop without terminating the bottom statement that has not been executed, break ends the entire loop process

Guess you like

Origin blog.csdn.net/bj_zhb/article/details/104669676