Python's process control --if ... else ...

Python's process control --if ... else ...

First, the flow control

If the program likened to walk, then we up to now, has always followed a straight road, have not encountered too much fork. When confronted with the fork, you have to decide which fork in the road is your way to go, if we want the program to be able to handle such a judgment, how to do? Very simple, just a preset number of conditional statements in the program, which went condition which fork in the road, a process called flow control to meet.

In almost every programming language, there will be if ... else ..., can be divided into single branch, double-branch, multi-branch.

Second, a single branch

if 条件:
    满足条件后要执行的代码

Third, the two-branch

if 条件:
    满足条件后要执行的代码
else:
    不满足if后面的条件就走这里的代码

Insertion knowledge - indent:

You will find that the above code, the next row in each condition indented four spaces, which is why? This is a major feature of Python, forcing indentation, the purpose is to let the program know that each piece of code depends on what conditions, if not distinguished by indentation, does not know when your condition is met, what code execution to go.

In other programming languages, most of them by {}determining a block of code, such as C, C ++, Java and so on. In this case, the role of the indentation just make the code became clean.

Python is a very simple language, the inventors feel that the use turtle t should be {}ugly, it is not simply a straight, direct use indentation to distinguish the code blocks, i.e. indentation force.

Python indentation has the following principles:

  • The top line of top-level code must be written, that is, if a line of code itself does not depend on any conditions, then it must not make any indent.
  • The same level of code indentation must be consistent.
  • The official suggested indent with four spaces, of course, you can also use two (if you want to be a joke the words of others).

Fourth, multi-branch

if 条件1:
    满足条件1后要执行的代码
elif 条件2:
    满足条件2后要执行的代码
elif 条件3:
    满足条件3后要执行的代码
......
else:
    上面的条件都不满足后执行的代码

Note: If a plurality of conditions are satisfied, only match from the first condition satisfies down, and executes the code inside, and then exit the current control statements throughout this process does not proceed to determine which of the conditions.

Guess you like

Origin www.cnblogs.com/Kwan-C/p/11442339.html