Lecture 37: Core concepts and case demonstrations of Python if-elif-else flow control statements

1. The concept of process control

In 1996, computer scientists proved the fact that any simple or complex algorithm is composed of three basic structures: sequence structure, selection structure, and loop structure. Process control corresponds to the selection structure.

  • Sequential structure: The program executes the code sequentially from top to bottom, without any judgment or jump in the middle, until the end of the program, codes in any language are executed sequentially from top to bottom.
  • Selection structure: The program judges the boolean value returned by the result according to the condition, so as to selectively execute part of the code and realize the flow control.
  • Loop structure: The program repeatedly executes a certain piece of code according to the loop condition until the loop condition is not satisfied.

There is nothing wrong with the sequential structure, and the default is to execute the code in the order from top to bottom.

The selection structure is a concept related to process control and condition judgment. A program must have some process control, such as selectively executing part of the code according to the status of the business and the operation of the user, so as to achieve a certain effect.

A simple flow control is as shown in the figure below: first select the server to be operated, then enter the account password of the server, and then there will be a flow control to judge whether the entered account password is correct, if the result of the condition judgment is True, then log in Go to the console of the server, otherwise the result is False, then it will prompt to refuse to log in, and there is a second process control to judge whether to close the console, if the Boolean value of the condition judgment is False, then perform other operations, if it is True, then Disconnect.

image-20220812220705932

2. Notes on code blocks in Python

In a programming language, a code block is equivalent to a set of statements. The beginning and end of a code block are specified by a special character, such as starting with { and ending with }.

In Python, the beginning of a code block is represented by a colon. All lines in the code block must be indented with the same number of spaces, usually 4 spaces. If there is no index, an exception will be thrown, indicating a syntax error. Like the Yaml file format, you must index when indenting, and don't add it when there is no need for indexing.

3. Grammatical format of if flow control statement

1) Single-branch if flow control syntax structure

Single-branch if flow control is the simplest flow control, and single-branch refers to only one conditional judgment. The grammatical structure is as follows:

if 条件判断:
    条件执行体

Single-branch if statement execution flow: If the result of the conditional judgment is True, then execute the code block in the conditional execution body, and continue to execute the code behind the if statement after the execution is completed. If the result of the conditional judgment is False, then skip the condition The code in the execution body directly executes the code behind the if statement.

2) The grammatical structure of single-branch if statement + else

The else statement is equivalent to the clause of if, because the else statement is not an independent whole, but a part of the if statement. The else statement indicates that when no branch in the flow control satisfies the condition, then the code block corresponding to the else statement is executed. The else statement will be placed at the end of the if statement. The syntax format is as follows:

if 条件判断:
    条件执行体1
else:
	条件执行体2

Execution flow of single-branch if statement + else: If the result of the conditional judgment is True, then execute the code in the conditional execution body 1. After the execution is completed, continue to execute the code behind the if statement, and skip the corresponding else statement Code block, if the result of the conditional judgment is False, then execute the code block in the else statement, and continue to execute the code behind the if statement after the execution is completed.

3) Multi-branch if flow control syntax structure

If there are more than two conditional judgment branches in the if statement, it is called a multi-branch if flow control structure. Multiple elif statements can be added to the if statement, and the elif statement is shorthand for else if. The syntax format is as follows:

if 条件判断1:
    条件执行体1
elif 条件判断2:
    条件执行体2
elif 条件判断3:
    条件执行体3
......
elif 条件判断n:
    条件执行体n
else:
    条件执行体n

Multi-branch if flow control execution flow:

  • First, judge from conditional judgment 1. If the result of conditional judgment 1 is True, then execute the code in conditional execution body 1. After the execution is completed, continue to execute the code after the if statement. At this time, the process judgment branch behind the if statement The process control of elif will not be executed, which means that the conditions have been met, and the relevant code has been executed, so there is no need to judge.
  • If the result of conditional judgment 1 is False, then it depends on whether the result of elif conditional judgment 2 is True, and if it is True, then the code in conditional execution body 2 is executed.
  • Judgment layer by layer, as long as you find a branch that meets the conditions, and then execute the corresponding code block.
  • If there is no if or elif branch that satisfies the condition, then the code block corresponding to the else statement is executed.

After the code in the code block is executed, it is equivalent to the end of the judgment, and other codes after the if statement are executed.

As long as the return value is a Boolean type: True or False, flow control can be performed.

4. Simple use of if process control

The following is a simple use of the if flow control statement first, and then I will write some demand cases, and then we will learn more about the if flow control.

4.1. Single-branch if flow control statement

First complete a simple if flow control statement.

Requirement: To judge the quality score of an article, if the quality score is as high as 95, this article is allowed to be on the hot list.

article_quality = 97

#如果article_quality的值大于95,则输出文章质量的分数,然后提示其允许上热榜
if article_quality > 95:
    #返回的内容通过格式化字符串输出
    aq_format = '这篇文章的质量分是:{}, 允许上热榜'
    print(aq_format.format(article_quality))
    
#输出结果:这篇文章的质量分是:97, 允许上热榜

When the quality score of the article is greater than 95, it will return the quality score of the article, and then prompt to allow the hot list.

image-20220812232949570

4.2. If flow control with else statement

Add an else clause in the flow control statement, and when the condition does not meet any condition in the flow control, execute the code in the else code block.

Requirements: Determine the quality score of an article. If the quality score is as high as 95, print the quality score of the article and prompt to allow this article to be on the hot list. If the conditions are not met, also output the quality score of this article and prompt the article How much the quality score differs from the standard quality.

article_quality = 92

#如果质量分大于95,则输出文章的质量分,并提示允许上热榜
if article_quality > 95:
    #打印的内容由格式化规则存储,传递实际的分数到格式化字符串,最终打印
    aq_format = '这篇文章的质量分是:{}, 允许上热榜'
    print(aq_format.format(article_quality))
#如果质量分不满足条件,则输出文章的质量分,并计算该文章的质量分与标准质量分的差值,最终一并提示给用户
else:
    aq_format = '这篇文章的质量分是:{0}, 与标准分相差{1}, 再接再厉哟'
    #标准质量分为95,用95减去文章的质量分,得到差值
    diff = 95 - article_quality
    #打印的内容都在格式化规则内,利用format方法传递实际值,最终返回给用户
    print(aq_format.format(article_quality, diff))

Specify the quality score of this article to be 92, and then judge by the if process control. When it is greater than 95, return the quality score of the article and prompt to allow the hot list, otherwise return the quality score of the article and calculate The difference with the standard score will be returned to the user.

image-20220812234149781

4.3. Multi-branch if process control

The multi-branch if flow control means that there are multiple judgment conditions in the if statement, and judgments are made sequentially from top to bottom. When one of them is satisfied, the following judgments are not executed.

need:

  • The quality score is manually entered by the user and is not hard-coded.

  • When the article quality score is below 50, it indicates that the article quality is not good, which may affect the recommendation.

  • When the quality of the article is between 60 and 80, it indicates that the quality of the article needs to be improved, so keep going.

  • When the quality of the article is between 80 and 90, it indicates that the quality of the article has taken a big step forward, and continue to work hard.

  • When the article quality score is above 90, it indicates that the article quality is very good.

  • Otherwise, it will prompt that the parameter is invalid

Idea analysis:

  • The quality score is required to be manually input by the user and cannot be hard-coded, so a standard input data can be accepted through the input() function.
  • We need to consider whether the data received by the input() function meets our scenario. We need to judge the size of the quality score. The data received by the input function is a string type, so we also need to judge whether the string received by the input() function is all It is a number, which can be judged by the isdigit() method.
  • When all the strings passed in by the input function are numbers, then the string is converted into a number type through the int() function, and then assigned to the variable, otherwise it cannot participate in the comparison operation, if the string passed in is not Number, then the user will be prompted that the parameter is invalid, please enter a number.
  • After the preliminary judgment is completed, the follow-up is very simple, and the corresponding code is executed according to the size of the quality score.

The complete code for this case is as follows:

#质量分通过input函数由用户手动输入
article_quality = input('请输入文章的质量分:')

#input函数输入的数据类型是字符串,要判断字符串中是否全部为数字组成
if article_quality.isdigit():
    #已经证明传入的字符串全部由数字组成,将字符串类型转换成数字类型,否则后续判断就会异常
    article_quality = int(article_quality)
#如果传入的字符串不是全部由数字组成,那么就提示参数不合法,从而退出程序
else:
    print('参数不合法,请输入数字')
    exit()      #退出程序

#判断质量分是否小于60
if article_quality < 60:
    aq_format = '这篇文章的质量分是:{}, 文章质量不佳可能会影响推荐'
    print(aq_format.format(article_quality))
#判断质量分是否大于等于60并且小于80
elif article_quality >= 60 and article_quality < 80:
    aq_format = '这篇文章的质量分是:{}, 文章质量还有待提升继续加油'
    print(aq_format.format(article_quality))
#判断质量分是否大于等于80并且小于90
elif article_quality >= 80 and article_quality < 90:
    aq_format = '这篇文章的质量分是:{}, 文章质量已经跨进一大步了持续努力'
    print(aq_format.format(article_quality))
#判断质量分是否大于等于90
elif article_quality >= 90 and article_quality <= 100:
    aq_format = '这篇文章的质量分是:{}, 文章质量很好'
    print(aq_format.format(article_quality))
#其余分数则执行如下代码
else:
    print('分数太高了,不合理')

The code runs, enter the data to be passed in after the colon, if the data is not a number, the return parameter is invalid, please enter a number.

image-20220813103301174

When the incoming data is a reasonable value, run the part of the code that meets the condition.

image-20220813103335430

When the value passed in exceeds the maximum range, the maximum range is only 100, and some codes that do not meet the conditions are allowed at this time.

image-20220813103440168

When writing code, I will judge whether the strings passed in by the input() function are all composed of numbers, and the flow control between the quality partitions is separated separately. In order to enhance the readability of the code, these two Process control merging is implemented by nesting if. This method is recommended, but don't nest too much. The code is as follows:

#质量分通过input函数由用户手动传入
article_quality = input('请输入文章的质量分:')

#input函数输入的数据类型是字符串,要判断字符串中是否全部为数字组成
if article_quality.isdigit():
    #已经证明传入的字符串全部由数字组成,将字符串类型转换成数字类型,否则后续判断就会异常
    article_quality = int(article_quality)
    #下面开始对质量分的大小进行判断
    if article_quality < 60:
        aq_format = '这篇文章的质量分是:{}, 文章质量不佳可能会影响推荐'
        print(aq_format.format(article_quality))
    elif article_quality >= 60 and article_quality < 80:
        aq_format = '这篇文章的质量分是:{}, 文章质量还有待提升继续加油'
        print(aq_format.format(article_quality))
    elif article_quality >= 80 and article_quality < 90:
        aq_format = '这篇文章的质量分是:{}, 文章质量已经跨进一大步了持续努力'
        print(aq_format.format(article_quality))
    elif article_quality >= 90 and article_quality <= 100:
        aq_format = '这篇文章的质量分是:{}, 文章质量很好'
        print(aq_format.format(article_quality))
    else:
        print('分数太高了,不合理')
#如果传入的字符串不是全部由数字组成,那么就提示参数不合法,从而退出程序
else:
    print('参数不合法,请输入数字')
    exit()      #退出程序

For elif, you can also use nesting to achieve it, but the readability of the code will be very poor. It is equivalent to not using elif. Using if under else can be used for learning. It is not recommended to write code like this in actual development. Readability Very poor, the code is as follows:

article_quality = input('请输入文章的质量分:')

if article_quality.isdigit():
    article_quality = int(article_quality)
    if article_quality < 60:
        aq_format = '这篇文章的质量分是:{}, 文章质量不佳可能会影响推荐'
        print(aq_format.format(article_quality))
    else:
        if article_quality >= 60 and article_quality < 80:
            aq_format = '这篇文章的质量分是:{}, 文章质量还有待提升继续加油'
            print(aq_format.format(article_quality))
        else:
            if article_quality >= 80 and article_quality < 90:
                aq_format = '这篇文章的质量分是:{}, 文章质量已经跨进一大步了持续努力'
                print(aq_format.format(article_quality))
            else:
                if article_quality >= 90 and article_quality <= 100:
                    aq_format = '这篇文章的质量分是:{}, 文章质量很好'
                    print(aq_format.format(article_quality))
                else:
                    print('分数太高了,不合理')
else:
    print('参数不合法,请输入数字')
    exit()

It is recommended to use the method of elif, the code readability is good

image-20220813105235887

4.4. Multi-branch if code optimization

For the comparison operator with multiple conditions, it can also be abbreviated as follows:

80 <= article_quality < 90

代码含义:article_quality值小于等于80且小于90,换句话说就是article_quality值在80~90
要注意这种代码的写法,值1 <= 现有值 <2

Mainly to optimize the code of the comparison operation, the code is as follows:

#input函数输入的数据类型是字符串,要判断字符串中是否全部为数字组成
if article_quality.isdigit():
    #已经证明传入的字符串全部由数字组成,将字符串类型转换成数字类型,否则后续判断就会异常
    article_quality = int(article_quality)
    #下面开始对质量分的大小进行判断
    if article_quality < 60:
        aq_format = '这篇文章的质量分是:{}, 文章质量不佳可能会影响推荐'
        print(aq_format.format(article_quality))
    elif 60 <= article_quality < 80:
        aq_format = '这篇文章的质量分是:{}, 文章质量还有待提升继续加油'
        print(aq_format.format(article_quality))
    elif 80 <= article_quality < 90:
        aq_format = '这篇文章的质量分是:{}, 文章质量已经跨进一大步了持续努力'
        print(aq_format.format(article_quality))
    elif 90 <= article_quality <= 100:
        aq_format = '这篇文章的质量分是:{}, 文章质量很好'
        print(aq_format.format(article_quality))
    else:
        print('分数太高了,不合理')
#如果传入的字符串不是全部由数字组成,那么就提示参数不合法,从而退出程序
else:
    print('参数不合法,请输入数字')
    exit()      #退出程序

5. Boolean value of object

In Python, any object has its corresponding Boolean value, True or False, we can call the built-in function bool() to get the Boolean value of the object.

When the object is: False, value 0, None, empty string, empty list, empty tuple, empty dictionary, empty collection, the corresponding Boolean values ​​are False, and the Boolean values ​​of all remaining objects are True.

An object with a boolean value of False:

>>> bool(False)
False

>>> bool(0)
False
>>> bool(0.0)
False

>>> bool(None)
False

>>> bool('')
False
>>> bool("")
False

>>> bool([])
False

>>> bool(list())
False

>>> bool(())
False

>>> bool(tuple())
False

>>> bool({
    
    })
False

>>> bool(dict())
False

>>> bool(set())
False

>>> bool(frozenset())
False

Objects with a boolean value of True:

>>> bool(22)
True

>>> bool('jiangxl')
True

>>> bool('     ')
True

>>> bool([1,2,3])
True

>>> bool((1,2,3))
True

>>> bool({
    
    '1': 12, '2':13})
True

>>> bool({
    
    1,2,3,4})
True

In Python, all objects can be directly judged logically with Boolean values, and the interpreter will automatically call the built-in function bool() for conversion, without manually converting with the bool function.

if 99:
    print(99, True)

6.if-else conditional expression

6.1.if-else conditional expression syntax

The if-else conditional expression is, in layman's terms, the abbreviated mode of the if-else statement, similar to the ternary conditional operator in the C language.

Syntax format of conditional expression:

#单if-else条件表达式的语法格式
x if 判断条件 else y

#嵌套if-else条件表达式的语法格式
x if 判断条件1 else (z if 判断条件2 else y)

The execution order of the single if-else conditional expression: when the result of the judgment condition is True, the return value of the conditional expression is x, otherwise it returns y.

The execution order of nested if-else conditional expressions: when the result of judging condition 1 is True, the return value of the conditional expression is x, otherwise continue to see whether the result of judging condition 2 is True, and return z if it is True. Otherwise return y.

6.2. Single if-else conditional expression case

Requirement: If the quality score of the article is greater than or equal to 80, return excellent, otherwise return poor.

article_quality = 88

#当article_quality >=80判断结果为True时,返回优秀,否则返回不佳
result = '优秀' if article_quality >=80 else '不佳'

print(result)
#输出结果:优秀

This conditional expression is equivalent to the following code, which is equivalent to:

article_quality = 88
if article_quality >= 80:
    result = '优秀'
else:
    result = '不佳'
print(result)

In short, conditional expressions are shorthand for if-else statements, depending on personal preference.

6.3. Nested if-else conditional expression case

need:

  • If the quality score of the article is below 60, the quality of the returned article is not good.
  • If the quality of the article is scored between 60 and 80, it indicates that the quality of the article is good.
  • If the quality of the article is divided between 80 and 100, it indicates that the quality of the article is excellent.
article_quality = 88

'''
    如果article_quality < 60结果为True,质量分小于60,则打印文章质量不佳,如果不满足此条件,则执行else后面的语句。
    如果60 <= article_quality <= 80的结果为True,质量分在60~80之间,则打印文章质量良好,如果不满足此条件,则执行嵌套if中的else语句,最终返回文章质量优秀。
'''
result = '文章质量不佳' if article_quality < 60 else ('文章质量良好' if 60 <= article_quality <= 80 else '文章质量优秀')

print(result)
#输出结果:优秀

Nested conditional expressions are equivalent to the following code:

article_quality = 88

if article_quality < 60:
    result = '文章质量不佳'
else:
    if 60 <= article_quality <= 80:
        result = '文章质量良好'
    else:
        result = '文章质量优秀'
        
print(result)

7. if not statement

The if not statement can determine whether the Boolean value of a condition is False, and if it is False, execute the corresponding code.

By default, the if statement judges whether the Boolean value of the condition is True, and if not can judge whether the Boolean value of the condition is False.

article_quality = input('请输入文章的质量分:')

#如果article_quality.isdigit()条件的返回值是False,则打印
if not article_quality.isdigit():
    print('参数不合法')
    exit()
else:
    print(article_quality)

Guess you like

Origin blog.csdn.net/weixin_44953658/article/details/130335165