Python if statement nesting (required for getting started)

Time:2022-1-2

Nest if else statements in the simplest if statements, as follows:

If expression 1:
If expression 2:
Code block 1
    else:
Code block 2

For another example, if else statements are nested in if else statements. The form is as follows:

If expression 1:
If expression 2:
Code block 1
    else:
Code block 2
else:
If expression 3:
Code block 3
    else:
Code block 4

Python #, if, if else, and if elif else can be nested with each other. Therefore, when developing programs, you need to select the appropriate nesting scheme according to the needs of the scene. It should be noted that when nesting with each other, we must strictly abide by the indentation specifications of code blocks at different levels.

[example] judge whether it is drunk driving
If specified, the blood alcohol content of the vehicle driver is less than 20mg / 100mL, which does not constitute drunk driving; Alcohol content greater than or equal to 20mg / 100ml is drunk driving; Alcohol content greater than or equal to 80mg / 100ml is drunk driving. First write a python program to determine whether it is drunk driving.

By combing the ideas, the limit value of whether it constitutes drunk driving is 20mg / 100ml; In the range determined as drunk driving (greater than 20mg / 100ml), the limit value of drunk driving is 80mg / 100mL, and the whole code execution process should be shown in Figure 1.

 

Thus, we can nest two if else statements:

Proof = int (input)
if proof < 20:
    Print ("driver does not constitute drunk driving")
else:
    if proof < 80:
        Print ("driver has constituted drunk driving")
    else:
        Print ("the driver has constituted drunk driving")

The operation result is:

Enter the driver’s alcohol content per 100ml of blood: 10
Drivers do not constitute drunk driving

Of course, this example can also be implemented by using if elif else alone. This is just to make beginners familiar with the use of if branch nesting.

In addition, loop structures can also be nested in if branch structures. Similarly, branch structures can also be nested in loop structures.

End benefits

Here is a free set of 2020 latest Python introduction to advanced project practical video tutorial. Click here to get it!Or join the blogger Python exchange circle (QQ group: 1049600759) for free download.


 

The text and pictures of this article come from the Internet and their own ideas. They are only for learning and communication. They do not have any commercial use. The copyright belongs to the original author. If you have any questions, please contact us in time for handling.