Python Introductory Tutorial | Python Flow Control Statements

Three Structures of Program Flow Control

1. Sequential structure

The computer executes the program step by step from top to bottom
insert image description here

2. Select structure (conditional control)

A Python conditional statement is a block of code that is determined by the execution result (True or False) of one or more statements.

You can simply understand the execution process of the conditional statement through the following figure:
​Codeinsert image description here
execution process:
insert image description here

if statement

The general form of an if statement in Python is as follows:

if condition_1:
    statement_block_1
elif condition_2:
    statement_block_2
else:
    statement_block_3
  • If "condition_1" is True, the "statement_block_1" block statement will be executed
  • If "condition_1" is False, "condition_2" will be judged
  • If "condition_2" is True the "statement_block_2" block statement will be executed
  • If "condition_2" is False, the "statement_block_3" block statement will be executed

In Python, elif is used instead of else if, so the keywords of the if statement are: if – elif – else.

Note :

  • 1. A colon: should be used after each condition, indicating that the following is the statement block to be executed after the condition is met.
  • 2. Use indentation to divide statement blocks, and statements with the same indentation number form a statement block together.
  • 3. There is no switch...case statement in Python, but match...case is added in Python3.10 version, and the function is similar, see below for details.

Gif Demo:
insert image description here
Example The
following is a simple if example:

var1 = 100
if var1:
    print ("1 - if 表达式条件为 true")
    print (var1)
 
var2 = 0
if var2:
    print ("2 - if 表达式条件为 true")
    print (var2)
print ("Good bye!")

Execute the above code, the output is:

1 - if expression condition is true
100
Good bye!

From the result, we can see that because the variable var2 is 0, the corresponding if statement is not executed.

The following example demonstrates the dog's age calculation judgment:

age = int(input("请输入你家狗狗的年龄: "))
print("")
if age <= 0:
    print("你是在逗我吧!")
elif age == 1:
    print("相当于 14 岁的人。")
elif age == 2:
    print("相当于 22 岁的人。")
elif age > 2:
    human = 22 + (age -2)*5
    print("对应人类年龄: ", human)
 
### 退出提示
input("点击 enter 键退出")

Save the above script in the dog.py file and execute the script:

C:\Users\Lenovo>cd Desktop

C:\Users\Lenovo\Desktop>python dog.py
请输入你家狗狗的年龄: 6

对应人类年龄:  42
点击 enter 键退出

The following are commonly used operation operators in if:

operator describe
< less than
<= less than or equal to
> more than the
>= greater than or equal to
== equals, compares whether two values ​​are equal
!= not equal to
# 程序演示了 == 操作符
# 使用数字
print(5 == 6)
# 使用变量
x = 5
y = 8
print(x == y)

The output of the above example:

False
False

The high_low.py file demonstrates comparison operations for numbers:

# 该实例演示了数字猜谜游戏
number = 7
guess = -1
print("数字猜谜游戏!")
while guess != number:
    guess = int(input("请输入你猜的数字:"))
 
    if guess == number:
        print("恭喜,你猜对了!")
    elif guess < number:
        print("猜的数字小了...")
    elif guess > number:
        print("猜的数字大了...")

Execute the above script, the example output is as follows:

C:\Users\Lenovo\Desktop>python high_low.pyNumber
guessing game!
Please enter the number you guessed: 2
The number guessed is small...
Please enter the number you guessed: 3
The number guessed is small...
Please enter your guess Number: 9
The guessed number is too big...
Please enter the number you guessed: 7
Congratulations, you guessed it right!

nested if

In nested if statements, you can place an if...elif...else structure inside another if...elif...else structure.

if 表达式1:
    语句
    if 表达式2:
        语句
    elif 表达式3:
        语句
    else:
        语句
elif 表达式4:
    语句
else:
    语句

Script Mode Example

num=int(input("输入一个数字:"))
if num%2==0:
    if num%3==0:
        print ("你输入的数字可以整除 2 和 3")
    else:
        print ("你输入的数字可以整除 2,但不能整除 3")
else:
    if num%3==0:
        print ("你输入的数字可以整除 3,但不能整除 2")
    else:
        print  ("你输入的数字不能整除 2 和 3")

Save the above program to the test_if.py file, and the output after execution is:

C:\Users\Lenovo\Desktop>python test.py
Enter a number: 5
The number you entered cannot be divided by 2 and 3

match…case

Python 3.10 adds the conditional judgment of match...case, no need to use a series of if-else to judge.

The object after match will be matched with the content after case in turn. If the match is successful, the matched expression will be executed, otherwise it will be skipped directly. _ can match everything.

The syntax format is as follows:

match subject:
    case <pattern_1>:
        <action_1>
    case <pattern_2>:
        <action_2>
    case <pattern_3>:
        <action_3>
    case _:
        <action_wildcard>

case _ : Similar to default : in C and Java , when other cases cannot be matched, match this one, and it is guaranteed that the match will always be successful.

def http_error(status):
    match status:
        case 400:
            return "Bad request"
        case 404:
            return "Not found"
        case 418:
            return "I'm a teapot"
        case _:
            return "Something's wrong with the internet"

mystatus=400
print(http_error(400))

The above is an example of outputting the HTTP status code, and the output result is:

Bad request

A case can also set multiple matching conditions, the conditions are separated by |, for example:

...
    case 401|403|404:
        return "Not allowed"

3. Loop structure

The loop statements in Python are for and while.

The control structure diagram of the Python loop statement is as follows:
insert image description here

while loop

The general form of the while statement in Python:

while 判断条件(condition):
    执行语句(statements)……

The execution flow chart is as follows:

如果条件为true
继续判断
如果条件为false
开始
判断条件
执行代码块
结束

Executing the Gif demo:
insert image description here
Also note the colons and indentation. Also, there is no do…while loop in Python.

The following example uses while to calculate the sum from 1 to 100:

n = 100
sum = 0
counter = 1
while counter <= n:
    sum = sum + counter
    counter += 1
 
print("1 到 %d 之和为: %d" % (n,sum))

The execution results are as follows:

The sum of 1 to 100 is: 5050

Infinite loop
We can achieve an infinite loop by setting the conditional expression to never be false, the example is as follows:

#!/usr/bin/python3
 
var = 1
while var == 1 :  # 表达式永远为 true
   num = int(input("输入一个数字  :"))
   print ("你输入的数字是: ", num)
 
print ("Good bye!")

Execute the above script, the output is as follows:

Enter a number: 5The
number you entered is: 5Enter
a number:

You can use C TRL+C to exit the current infinite loop.

Infinite loops are useful for real-time client requests on the server.

while loop using else statement

If the conditional statement after while is false, execute the statement block of else.

The syntax format is as follows:

while <expr>:
    <statement(s)>
else:
    <additional_statement(s)>

The statement block statement(s) is executed if the conditional statement of expr is true, and additional_statement(s) is executed if it is false.

Loop out the numbers and judge the size:

count = 0
while count < 5:
   print (count, " 小于 5")
   count = count + 1
else:
   print (count, " 大于或等于 5")

Execute the above script, the output is as follows:

0 less than 5
1 less than 5
2 less than 5
3 less than 5
4 less than 5
5 greater than or equal to 5

simple statement group

Similar to the syntax of the if statement, if there is only one statement in your while loop body, you can write the statement on the same line as the while, as follows:

flag = 1
while (flag): print ('欢迎访问泰山的技术博客!')
print ("Good bye!")

Note : You can use CTRL+C to interrupt the infinite loop above.

Execute the above script, the output is as follows:

Welcome to Tarzan's Tech Blog!
Welcome to Tarzan's Tech Blog!
Welcome to Tarzan's Tech Blog!
Welcome to Tarzan's Tech Blog!
Welcome to Tarzan's Tech Blog!
 …

for loop statement

A Python for loop can iterate over any iterable object, such as a list or a string.

The general format of a for loop is as follows:

for <variable> in <sequence>:
    <statements>
else:
    <statements>

flow chart:

下一个元素
继续
循环完所有元素
开始
集合中的元素
代码块
结束

Python for loop example:

sites = ["Baidu", "Google","Tarzan","Taobao"]
for site in sites:
    print(site)

The output of the above code execution is:

Baidu
Google
Tarzan
Taobao

Can also be used to print each character in a string:

word = 'Tarzan'
 
for letter in word:
    print(letter)

The output of the above code execution is:

t
a
r
z
a
n

Integer range values ​​can be used with the range() function:

#  1 到 5 的所有数字:
for number in range(1, 6):
    print(number)

The output of the above code execution is:

1
2
3
4
5

for…else

In Python, the for...else statement is used to execute a piece of code after the loop ends.

The syntax format is as follows:

for item in iterable:
    # 循环主体
else:
    # 循环结束后执行的代码

When the loop is executed (that is, all elements in the iterable are traversed), the code in the else clause will be executed. If a break statement is encountered during the loop, the loop will be interrupted, and the else clause will not be executed at this time.

for x in range(6):
  print(x)
else:
  print("Finally finished!")

执行脚本后,输出结果为:

0
1
2
3
4
5
6
Finally finished!

以下 for 实例中使用了 break 语句,break 语句用于跳出当前循环体,不会执行 else 子句:

sites = ["Baidu", "Google","Tarzan","Taobao"]
for site in sites:
    if site == "Tarzan":
        print("泰山博客!")
        break
    print("循环数据 " + site)
else:
    print("没有循环数据!")
print("完成循环!")

执行脚本后,在循环到 "Tarzan"时会跳出循环体:

循环数据 Baidu
循环数据 Google
泰山博客!
完成循环!

range() 函数

Python3 range() 函数返回的是一个可迭代对象(类型是对象),而不是列表类型, 所以打印的时候不会打印列表。
Python3 list() 函数是对象迭代器,可以把 range() 返回的可迭代对象转为一个列表,返回的变量类型为列表。

函数语法

range(stop)
range(start, stop[, step])

参数说明:

  • start: 计数从 start 开始。默认是从 0 开始。例如 range(5) 等价于 range(0, 5)
  • stop: 计数到 stop 结束,但不包括 stop。例如:range(0, 5) 是 [0, 1, 2, 3, 4] 没有 5
  • step:步长,默认为 1。例如:range(0, 5) 等价于 range(0, 5, 1)

如果你需要遍历数字序列,可以使用内置 range() 函数。它会生成数列,例如:

>>>for i in range(5):
...     print(i)
...
0
1
2
3
4

也可以使 range() 以指定数字开始并指定不同的增量(甚至可以是负数,有时这也叫做’步长’):

>>> for i in range(0, 10, 3):
...  print(i)
...
0
3
6
9

注意: print(i) 要缩进空格。
负数:

>>> for i in range(-10, -100, -30):
...  print(i)
...
-10
-40
-70
>>>

您可以结合 range() 和 len() 函数以遍历一个序列的索引,如下所示:

>>> a = ['Google', 'Baidu', 'Tarzan', 'Taobao', 'QQ']
>>> for i in range(len(a)):
...  print(i,a[i])
...
0 Google
1 Baidu
2 Tarzan
3 Taobao
4 QQ
>>>

还可以使用 range() 函数来创建一个列表:

>>>list(range(5))
[0, 1, 2, 3, 4]
>>>

break 和 continue 语句及循环中的 else 子句

break 执行流程图:
insert image description here
continue 执行流程图:
insert image description here
while 语句代码执行过程:
insert image description here
for 语句代码执行过程:
insert image description here
break 语句可以跳出 for 和 while 的循环体。如果你从 for 或 while 循环中终止,任何对应的循环 else 块将不执行。

continue 语句被用来告诉 Python 跳过当前循环块中的剩余语句,然后继续进行下一轮循环。

实例
while 中使用 break:

n = 0
while n < 5:
    n += 1
    if n == 3:
        break
    print(n)

输出结果为:

1
2

while 中使用 continue:

n = 0
while n < 5:
    n += 1
    if n == 3:
        continue
    print(n)

输出结果为:

1
2
4
5

更多实例如下:

for letter in 'Tarzan':     # 第一个实例
   if letter == 'z':
      break
   print ('当前字母为 :', letter)
  
var = 10                    # 第二个实例
while var > 0:              
   print ('当前变量值为 :', var)
   var = var -1
   if var == 5:
      break

执行以上脚本输出结果为:

当前字母为 : T
当前字母为 : a
当前字母为 : r
当前变量值为 : 10
当前变量值为 : 9
当前变量值为 : 8
当前变量值为 : 7
当前变量值为 : 6

以下实例循环字符串 Tarzan,碰到字母 z 跳过输出:

for letter in 'Tarzan':     # 第一个实例
   if letter == 'z':        # 字母为 o 时跳过输出
      continue
   print ('当前字母 :', letter)
 
var = 5                    # 第二个实例
while var > 0:              
   var = var -1
   if var == 3:             # 变量为 3 时跳过输出
      continue
   print ('当前变量值 :', var)

执行以上脚本输出结果为:

当前字母 : T
当前字母 : a
当前字母 : r
当前字母 : a
当前字母 : n
当前变量值 : 4
当前变量值 : 2
当前变量值 : 1
当前变量值 : 0

A loop statement can have an else clause, which is executed when the list is exhausted (in a for loop) or the condition becomes false (in a while loop) causing the loop to terminate, but not when the loop is terminated by a break.

The following example is used to query the cycle example of prime number:

for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print(n, '等于', x, '*', n//x)
            break
    else:
        # 循环中没有找到元素
        print(n, ' 是质数')

The output of executing the above script is:

2 is a prime number
3 is a prime number
4 is equal to 2 * 2
5 is a prime number
6 is equal to 2 * 3
7 is a prime number
8 is equal to 2 * 4
9 is equal to 3 * 3

pass statement

Python pass is an empty statement, in order to maintain the integrity of the program structure.

pass does not do anything, it is generally used as a placeholder statement, as shown in the following example

>>>while True:
...     pass  # 等待键盘中断 (Ctrl+C)

Minimal class:

>>>class MyEmptyClass:
...     pass

The following example executes the pass statement block when the letter is o:

for letter in 'Tarzan': 
   if letter == 'z':
      pass
      print ('执行 pass 块')
   print ('当前字母 :', letter)

The output of executing the above script is:

Current letter: TCurrent
letter: aCurrent
letter:
rExecute pass blockCurrent
letter: zCurrent
letter:
aCurrent letter: n

Guess you like

Origin blog.csdn.net/weixin_40986713/article/details/132683868