Python 简明教程

Python - Control Flow

Python 程序控制流受各种 conditional statementsloopsfunction 调用的控制。默认情况下,计算机程序中的指令将按顺序方式从上到下或从头到尾执行。但是,这种顺序执行程序只能执行一些简单的任务。我们希望程序具有决策能力,以便它可以根据不同的条件执行不同的步骤。

Python program control flow is regulated by various types of conditional statements, loops, and function calls. By default, the instructions in a computer program are executed in a sequential manner, from top to bottom, or from start to end. However, such sequentially executing programs can perform only simplistic tasks. We would like the program to have a decision-making ability, so that it performs different steps depending on different conditions.

包括 Python 在内的多数编程语言都提供了控制指令执行流的功能。通常,任何编程语言中都有两种控制流语句,Python 也支持这些语句。

Most programming languages including Python provide functionality to control the flow of execution of instructions. Normally, there are two type of control flow statements in any programming language and Python also supports them.

Decision Making Statements

决策语句用于 Python 程序中,以让它们能够决定执行哪组备用指令,具体取决于某个布尔表达式的值。

Decision making statements are used in the Python programs to make them able to decide which of the alternative group of instructions to be executed, depending on value of a certain Boolean expression.

下图说明了决策语句的工作方式:

The following diagram illustrates how decision-making statements work −

decision making statements

The if Statements

Python 提供 if..elif..else 控制语句作为决策标记的一部分。它包含三个不同的块,即 if 块、elif(else if 的缩写)块和 else 块。

Python provides if..elif..else control statements as a part of decision marking. It consists of three different blocks, which are if block, elif (short of else if) block and else block.

下面是一个使用 if..elif..else 的简单示例。您可以尝试使用不同的标记运行此程序并验证结果。

Following is a simple example which makes use of if..elif..else. You can try to run this program using different marks and verify the result.

marks = 80
result = ""
if marks < 30:
   result = "Failed"
elif marks > 75:
   result = "Passed with distinction"
else:
   result = "Passed"

print(result)

这将产生以下结果:

This will produce following result:

Passed with distinction

The match Statement

Python 支持 Match-Case 语句,该语句也可以用作决策的一部分。如果模式匹配表达式,那么该情况下的代码将执行。

Python supports Match-Case statement, which can also be used as a part of decision making. If a pattern matches the expression, the code under that case will execute.

以下是一个使用匹配语句的简单示例。

Following is a simple example which makes use of match statement.

def checkVowel(n):
   match n:
      case 'a': return "Vowel alphabet"
      case 'e': return "Vowel alphabet"
      case 'i': return "Vowel alphabet"
      case 'o': return "Vowel alphabet"
      case 'u': return "Vowel alphabet"
      case _: return "Simple alphabet"
print (checkVowel('a'))
print (checkVowel('m'))
print (checkVowel('o'))

这将产生以下结果:

This will produce following result:

Vowel alphabet
Simple alphabet
Vowel alphabet

Loops or Iteration Statements

大多数进程都需要重复执行一组指令。在编程术语中,这被称为 loop 。如果流程被重定向到较早的步骤,而不是下一步,它就构成了循环。

Most of the processes require a group of instructions to be repeatedly executed. In programming terminology, it is called a loop. Instead of the next step, if the flow is redirected towards any earlier step, it constitutes a loop.

下面的图表说明了循环是如何工作的:

The following diagram illustrates how the looping works −

looping works

如果控制无条件地返回,它就会形成一个无限循环,这是不希望的,因为剩余的代码永远无法得到执行。

If the control goes back unconditionally, it forms an infinite loop which is not desired as the rest of the code would never get executed.

在条件循环里,语句块的重复迭代将在特定条件得到满足前继续下去。Python 支持许多循环,例如 for 循环和 while 循环,我们将在下一章学习它们。

In a conditional loop, the repeated iteration of block of statements goes on till a certain condition is met. Python supports a number of loops like for loop, while loop which we will study in next chapters.

The for Loop

for loop 迭代任意序列(例如列表、元组或字符串)中的项目。

The for loop iterates over the items of any sequence, such as a list, tuple or a string .

以下是一个使用 For Loop 迭代 Python 中数组的示例:

Following is an example which makes use of For Loop to iterate through an array in Python:

words = ["one", "two", "three"]
for x in words:
  print(x)

这将产生以下结果:

This will produce following result:

one
two
three

The while Loop

while loop 在给定的布尔表达式为 True 的情况下重复执行目标语句。

The while loop repeatedly executes a target statement as long as a given boolean expression is true.

以下是一个使用 While Loop 在 Python 中打印前 5 个数字的示例:

Following is an example which makes use of While Loop to print first 5 numbers in Python:

i = 1
while i < 6:
  print(i)
  i += 1

这将产生以下结果:

This will produce following result:

1
2
3
4
5

Jump Statements

通过打破程序的当前流程,跳转语句可用于跳转到特定的语句。在 Python 中,有两个跳转语句 breakcontinue

The jump statements are used to jump on a specific statement by breaking the current flow of the program. In Python, there are two jump statements break and continue.

The break Statement

它终止当前循环,并在下一条语句处恢复执行。

It terminates the current loop and resumes execution at the next statement.

以下示例演示了 break 语句的使用:

The following example demonstrates the use of break statement −

x = 0

while x < 10:
    print("x:", x)
    if x == 5:
        print("Breaking...")
        break
    x += 1

print("End")

这将产生以下结果:

This will produce following result:

x: 0
x: 1
x: 2
x: 3
x: 4
x: 5
Breaking...
End

The continue Statement

它跳过程序块的执行,并将控制返回到当前循环的开始,以开始下一次迭代。

It skips the execution of the program block and returns the control to the beginning of the current loop to start the next iteration.

以下示例演示了 continue 语句的使用:

The following example demonstrates the use of continue statement −

for letter in "Python":
    # continue when letter is 'h'
    if letter == "h":
        continue
    print("Current Letter :", letter)

这将产生以下结果:

This will produce following result:

Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n