People often say that life is a process of constantly making multiple choice questions: some people have no choice and only have one way to go; some people are better and can choose one of the two; some people with good ability or good family background can choose There are more choices; there are also some people who will wander around in circles and cannot find their direction during the confused period of life. For those who believe in God, it is as if God has planned a life route for us in advance, and it is also as if the gods have set many hardships in advance for Tang Zeng’s master and disciples to learn scriptures. God and gods control everything. Programming language can simulate all aspects of human life. Programmers, like gods and gods, can control the execution process of the program through special keywords in the programming language. These keywords constitute the process control statement.
Flow in programming languageControl statements are divided into the following categories:
Sequential statements
Branch statements
LoopStatements
Among them, sequential statements do not It requires a separate keyword to control, which means it is executed line by line, and no special instructions are required. The main things to talk about here are branch statements and loop statements.
1. Branch Statement
Conditional branch statement is a code block that determines which branch to execute based on the execution result (True/False) of one or more statements (judgment conditions). The branch statements provided in Python are: if..else statement, and no switch..case statement is provided. The if..else statement has the following forms:
Single branch:
if judgment condition:
Code block
If the code block of the single branch statement has only one statement, you can write the if statement and the code On the same line:
if Judgment condition: One sentence of code
Example: Determine whether the specified uid is the root user
uid = 0 if uid == 0: print("root")
You can also write like this:
uid = 0 if uid == 0: print("root")
Output result: root
Dual branch:
if Judgment condition:
Code block
else:
Code block
Example: Print user identity based on user id
uid = 100 if uid == 0: print("root") else: print("Common user")
Output result: Common user
Multiple branches:
if Judgment condition 1:
Code block 1
elif Judgment condition 2:
Code block 2
...
elif Judgment condition n:
Code block n
else:
Default code block
Example: Print letter grade based on student score
score = 88.8 level = int(score % 10) if level >= 10: print('Level A+') elif level == 9: print('Level A') elif level == 8: print('Level B') elif level == 7: print('Level C') elif level == 6: print('Level D') else: print('Level E')
Output result: Level B
Explanation:
When the expression in the above "judgment condition" can be any expression or any type of data Object instance. As long as the "true" value of the final return result of the judgment condition tests to True, it means that the condition is established and the corresponding code block will be executed; otherwise, it means that the condition is not established and the next condition needs to be judged.
2. Loop Statement
When we need to execute a code statement or code block multiple times, we can use a loop statement. The loop statements provided in Python are: while loop and for loop. It should be noted that there is no do..while loop in Python. In addition, there are several loop control statements used to control the loop execution process: break, continue and pass.
1. while loop
Basic form
The basic form of while loop statement is as follows:
while judgment condition:
Code block
When the given judgment condition When the truth test result of the return value is True, the code of the loop body is executed, otherwise the loop body is exited.
Example: Print numbers 0-9 in a loop
count = 0 while count <= 9: print(count, end=' ') count += 1
Output result: 0 1 2 3 4 5 6 7 8 9
while infinite loop
When the judgment condition of while is always When True, the code in the while loop body will loop forever.
while True:
print("This is an infinite loop")
Output result:
This is an infinite loop
This is an infinite loop
This is an infinite loop
...
You can terminate the operation by Ctrl + C at this time.
while..else
Statement form:
while Judgment condition:
Code block
else:
Code block
The code block in else will be executed normally in the while loop If the while loop is interrupted by break, the code block in else will not be executed.
Example 1: The normal execution of the while loop ends (the statement in else will be executed)
count = 0 while count <=9: print(count, end=' ') count += 1 else: print('end')
The execution result is: 0 1 2 3 4 5 6 7 8 9 end
Example 2: The while loop is interrupted (the statement in else will not be executed)
count = 0 while count <=9: print(count, end=' ') if count == 5: break count += 1 else: print('end')
输出结果:0 1 2 3 4 5
2. for循环
for循环通常用于遍历序列(如list、tuple、range、str)、集合(如 set)和映射对象(如dict)。
基本形式
for循环的基本格式:
for 临时变量 in 可迭代对象:
代码块
实例:遍历打印一个list中的元素
names = ['Tom', 'Peter', 'Jerry', 'Jack'] for name in names: print(name)
对于序列,也通过索引进行迭代:
names = ['Tom', 'Peter', 'Jerry', 'Jack'] for i in range(len(names)): print(names[i])
执行结果:
Tom
Peter
Jerry
Jack
for...else
与while..else基本一致,不再赘述。
3. 循环控制语句
循环控制语句可以更改循环体中程序的执行过程,如中断循环、跳过本次循环。
循环控制语句 说明
break 终止整个循环
contine 跳过本次循环,执行下一次循环
pass pass语句是个空语句,只是为了保持程序结构的完整性,没有什么特殊含义。pass语句并不是只能用于循环语句中,也可以用于分支语句中。
实例1:遍历0-9范围内的所有数字,并通过循环控制语句打印出其中的奇数
for i in range(10): if i % 2 == 0: continue print(i, end=' ')
输出结果:1 3 5 7 9
实例2:通过循环控制语句打印一个列表中的前3个元素
names = ['Tom', 'Peter', 'Jerry', 'Jack', 'Lilly'] for i in range(len(names)): if i >= 3: break print(names[i])
输出结果:
Tom
Peter
Jerry
4. 循环嵌套
循环嵌套是指:在一个循环体里面嵌入另一循环。
实例1:通过while循环打印99乘法表
j = 1 while j <= 9: i = 1 while i <= j: print('%d*%d=%d' % (i, j, i*j), end='\t') i += 1 print() j += 1
实例2:通过for循环打印99乘法表
for j in range(1, 10): for i in range(1, j+1): print('%d*%d=%d' % (i, j, i*j), end='\t') i += 1 print() j += 1
输出结果:
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
The above is the detailed content of Python flow control statement methods. For more information, please follow other related articles on the PHP Chinese website!