[Python is not a python] Structured programming | Branch structure (if, etc.)

Ⅰ. Structured programming

0x00 If you can only use goto now

In the 1950s and 1960s, high-level languages ​​were not yet popular. Many people used assembly to write programs. Assembly code ran efficiently, but it had a fatal shortcoming: it was difficult to understand and difficult to maintain.

Programming is something that a few smart people do. They have superior intelligence and do not follow any rules when writing code. They can use the flexible and powerful Goto at will to write code that only they can understand.

Such code is not only extremely unreadable, but also extremely inefficient.

If I were to go back to that time, I'm afraid I wouldn't survive even one episode.

0x01 God comes to the rescue

In 1968, the "NATO Software Engineering Conference" was held in the picturesque German town of Garmisch. NATO's Science and Technology Committee convened nearly 50 leading programmers, computer scientists and industrial giants to discuss and formulate countermeasures to get rid of the "software crisis".

Whenever a crisis comes, someone will always come to the rescue, and this time it’s Dijkstra. I believe you must be familiar with him.

 After research, this great man published a paper that shocked the world - "Theory of the Harmful Go to Statement". He strongly urged the abandonment of the goto statement.

This paper immediately caused a stir in the programming world. Dijkstra was well prepared this time. He introduced a famous theory, which is also a modern programming technology:

No matter what the program is, no matter how complex it is, it can be expressed using three basic structures: sequence, branch, and loop.

 

0x02 Structured programming 

Dijkstra also coined a term: structured programming

Structured programming includes the following elements:

Control Structures: Sequence, Branching, Looping

Subroutine: A series of encapsulated functions

These are the basic elements of modern programming languages.

The debate over Go to has never stopped, including great masters like Bernard Kernard, who also got involved and published an article "Structured Programming with go to Statements". He analyzed many common programming tasks and found that using Go to will result in some of them. The most ideal structure. For example: jumping out of nested loops, jumping out of multiple branches, etc. Therefore, many programming languages ​​​​still retain the goto keyword (such as the everlasting C language).

But goto has been removed from Python.

Ⅱ.Branch structure

0x00 What is a branch structure?

Okay, I ran a little far. Let’s get back to the point.

So far, the Python code we have written is executed sequentially one statement at a time. This code structure is usually called a sequential structure. But only the sequential structure cannot solve all problems. At this time, we need the branch structure in structured programming!

What are the application scenarios of the branch structure: design a game, check whether the player's blood volume is still there, and output GameOver if not; log in to the system, and determine whether the password entered by the user is true or not...

After encountering the branch structure, I can only say one thing:

0x01 single branch structure 

To use the if keyword in a single branch structure in python

The basic format is as follows:

if 判断条件:
    代码块 # 代码为真就执行
# 否则就直接跳过

Let’s dissect this code first

What is true? Dear students, you can go back to the previous article to review the comparison. There are many comparison operators in Python. If the two numbers of the comparison operator match the comparison operator, then it is true, for example:

"a" == 1 # 输出:False
1 == 1 # 输出: True
1 > 1 # 输出:False
2 > 0.5 # 输出:True
not True # 输出:False

 It's very clear, if this condition is true.

Actually:

if 判断条件:
    代码块

Equivalent to

if bool(判断条件):
    代码块

We can see the code block part, and we will find that there is an extra indent in front of the code block.

What is indentation?

Strict code indentation is a major feature of Python syntax, just like the curly braces in the C language family (C, C++, Java, etc.), it is also very necessary in most situations. In many code specifications, there are also requirements for code writing to be line-wrapped and code indented according to certain rules, but these requirements are purely for the convenience of people (programmers) to read, use or modify. For compilers or interpreters , completely turning a blind eye.

But for the Python interpreter, the indentation before each line of code has grammatical and logical meaning. This feature of Python often causes controversy among Python users and non-Python users.

In fact, Python's forced code indentation is like a double-edged sword, with advantages and disadvantages. Obviously, the advantage is that under the strict requirements of code indentation, the code is very neat and standardized, pleasing to the eye, which improves readability and maintainability to a certain extent.

However, Python has strict code indentation. For people who have transferred from other languages, since the first language for computer and related majors is generally C/C++ or Java, their syntax styles are basically the same, so it may take a while. to adapt. Python code indentation is very strict. If the code is not written according to its rules, syntax errors may occur, such as unexpected indent, and sometimes logical errors may occur.

                                —— Quoted from Zhihu (the author forgot, if any readers know, please tell me so I can mark it)

Simply put, the code block executed by if is identified by indentation. This means that the following code is also possible

if 判断条件:
    语句A
    
    语句B # 这段代码也属于if为真要执行的语句

Note: In Python, you can use 4 spaces or a tab to represent an indent, but you cannot mix them, otherwise. . .

 

Let's try this single-branch structure:

s = input()

if s == "666": #判断是否输入了666
    print('输入了666')

 In fact, the if inside can be reduced to this code

s = input()

if s == "666": print('输入了666')

This is also possible.

0x02 Two-branch statement

Only relying on a single branch statement cannot solve all problems. For example: we need to determine whether a student's performance is qualified.

If we only use a single branch statement, we have to look like this:

if grade >= 60:
    print('及格')
if grade < 60:
    print('不及格,请家长!!!')

This is too cumbersome!

In order to solve this problem, the programming master invented a legendary statement-the two-branch statement!

There is an else keyword in the second branch statement

The basic syntax is as follows

if 判断条件:
    代码块1
else: # 如果上面的if判断为假就执行
    代码快2

Therefore, the sentence we started with can be simplified to this:

if grade >= 60:
    print('及格')
else:
    print('请家长!!!')



0x03 multi-branch structure

We still use the two-branch structure example from last time.

What if we want to divide it into smaller pieces?

if grade == 100:
    print('满分')
if 100 < grade >= 90:
    print('优秀')
if 90 < grade >= 80:
    print('良好')
if 80 > grade >= 60:
    print('及格')
if grade < 60:
    print('不及格') 

This code is bad, and its readability and writability are too poor!

How could the master keep reading and come up with a multi-branch statement in a few clicks?

The basic syntax of a multi-branch statement is as follows

if 判断条件1:
    代码块1
elif 判断条件2: # 如果上面所有的都未执行且该条件为真就执行
    代码块2
elif ... # elif的数量可以是无数多
else:
    代码块n

This is the best!

In this way, our code above becomes

if grade == 100:
    print('满分')
elif 100 < grade >= 90:
    print('优秀')
elif 90 < grade >= 80:
    print('良好')
elif 80 > grade >= 60:
    print('及格')
else:
    print('不及格') 

This is so handsome!

0x04 logical operator

We talked about logical operators in the previous lesson, they are as follows

Logical Operators Function
and AND operation
or OR operation
not NOT operation

1. and operator

Function of the and operator: Assume that x and y are two expressions. x and y means that when both expressions of x and y are true, the result of the operation is true. and can be intuitively understood as the meaning of and .

① When both sides are expressions:

example:

print(30>20 and 40>30)#运行结果为TRUE

print(30>20 and 4>30)#运行结果为FALSE

When both sides of and are expressions, this is easy to understand.

② When one side is a variable and the other side is an expression:

example:

print(20 and (c:=30)>20)#运行结果是TRUE

print(20 and (d:=20)>30)#运行结果为FALSE

③ When both sides are variables:

example:

a=20,b=30#那么print(a and b) 运行结果为 30

a=20,b=30#那么print(b and a) 运行结果为 20

This situation is actually the most difficult to understand. Follow the following train of thought.

First of all, the left side of the and operator is a, which is a variable rather than an expression, so there is no need to judge that the left side must be TRUE, and the situation on the right side is the same, so it is assumed that the results of both sides are TRUE.

This situation is defined in Python. When and goes from left to right, if all values ​​are true, the next value is returned. As long as there is a false value, the first false value is returned.

2. or operator

Function of the or operator: Suppose x and y are two expressions. x and y means that when one of the two expressions x and y is true, the result of the operation is true. When both expressions are false, the operation The result is false. or can be intuitively understood as meaning or .

① When both sides are expressions:

example:

print(30>20 or 40>30)#运行结果为TRUE

print(30>20 or 4>30)#运行结果为TRUE

print(3>20 or 4>30)#运行结果为FALSE

② When one side is a variable and the other side is an expression:

example:

print(20 or (c:=30)>20)#运行结果是20

print(20 or (d:=20)>30)#运行结果为20

③ When both sides are variables:

example:

print(20 or 30)#运行结果是20

print(30 or 20)#运行结果为30

3. not operator

The function of the not operator: Assume x is an expression. When x is true, the result of the operation is false. When x is false, the result of the operation is true. Not can intuitively understand the meaning of not or incorrect .

example:

print(not(20>10))#运行结果为FALSE

print(not(10>20))#运行结果为TRUE

0x04 Priority of logical operators

Logical operators in Python have priorities. The priority rule is not>and>or . When there are multiple logical operators in a statement, the operation must be performed according to this priority.

example:

print(not(20 or 30) and 30>20)

The result of the operation is FALSE

 

Guess you like

Origin blog.csdn.net/m0_73552311/article/details/133042572