"Learning Python with You Hand in Hand" 15-judgment statement if

In the previous article "Learning Python with You Hand in Hand " 14-Interactive Input , we learned about the method of using the input() function to achieve interactive input with a computer, and learned how to use PyCharm to write and run programs.

In addition, at the end of the last article, I left a question for everyone, that is, how to change the line for the user to input after the prompt content is displayed. Is the answer very simple? Just add a newline character "\n" at the end of the prompt content string.

Starting from this article, I will work with you to apply the knowledge learned in the past in the process of learning control flow statements, and write some of our own small programs, so that everyone can truly enter the ranks of programmers.

The control flow statement we will introduce today is the judgment statement if, which can also be called a conditional statement, which has the same meaning.

A typical if statement structure is as follows:

if 判断条件:
    执行语句1
else:
    执行语句2

Not to mention the grammatical structure of this rule, its meaning is well understood, and translated into natural language is:

If the judgment condition is true, execute statement 1, otherwise (that is, the judgment condition is false) execute statement 2.

Use the flowchart to express, it is more clear:

 

Among them, the keyword if is necessary, and the else can be omitted. That is, the statement is executed when the judgment condition is true, and nothing is executed when the judgment condition is false.

Regarding the if statement, the following knowledge points need to be introduced:

1. Judgment conditions:

As long as the output result is a Boolean operation (that is, True or False), it can be used as a judgment condition. For example, the comparison operations we learned before (>, >=, <, <=, ==, !=), member operations (in, not in), identity operations (is, not is), etc., among which the most commonly used are It is a comparison operation.

Since the interface of Jupyter Notebook is more friendly when demonstrating the examples, we still use Jupyter Notebook to demonstrate the examples first during the learning process of knowledge points, and we will use PyCharm when we finally write the program. (This approach will also be adopted in future articles.)

In [1]: if 2 > 1:   # 比较运算
            print("判断条件为真。")
        else:
            print("判断条件为假。")
Out[1]: 判断条件为真。
​
In [2]: if 1 in [2, 3, 4]:   # 成员运算
            print("判断条件为真。")
        else:
            print("判断条件为假。")
Out[2]: 判断条件为假。
​
In [3]: a = 257
        b = 257
        if a is b:   # 身份运算,为什么判断条件为假?请参考《手把手陪您学Python》13——运算
            print("判断条件为真。")
        else:
            print("判断条件为假。")
Out[3]: 判断条件为假。

If you need to judge multiple conditions at the same time, you also need to use logical operations (and, or, not).

In [4]: if 2 > 1 and 3 < 2:   # 逻辑运算and
            print("判断条件为真。")
        else:
            print("判断条件为假。")
Out[4]: 判断条件为假。
​
In [5]: if 2 > 1 or 3 < 2:   # 逻辑运算or
            print("判断条件为真。")
        else:
            print("判断条件为假。")
Out[5]: 判断条件为真。
​
In [6]: if not 2 > 1:   # 逻辑运算not
            print("判断条件为真。")
        else:
            print("判断条件为假。")
Out[6]: 判断条件为假。
​
In [7]: if not 2 > 1 and 3 > 2 or (4 > 3 and 3 < 5):   # 混合逻辑运算
            print("判断条件为真。")
        else:
            print("判断条件为假。")
Out[7]: 判断条件为真。

In addition, as mentioned before, 0 can represent False, and non-zero numbers can represent True, so theoretically operations that use numbers as output values ​​can be used as judgment conditions. It's just that such a judgment condition has no meaning. No one writes a program like that. You can use the comparison function a == 0 or a != 0 instead as the judgment condition.

In [8]: if 2 * 3:   # 数字运算,只要结果不为零就为真,一般不这样设置判断条件
            print("判断条件为真。")
        else:
            print("判断条件为假。")
Out[8]: 判断条件为真。
​
In [9]: a = 2 * 3
        if a != 0:   # 使用a == 0或者a != 0,作为判断条件
            print("判断条件为真。")
        else:
            print("判断条件为假。")
Out[9]: 判断条件为真。

2. Multi-condition judgment

The if...else.. we introduced before is a typical if statement structure, but the commonly used if statement structure also includes a judgment condition identifier such as elif. Moreover, multiple condition judgments can be realized by using multiple elifs. The sentence structure is as follows:

if 判断条件1:
    执行语句1
elif 判断条件2:
    执行语句2
elif 判断条件3:
    执行语句3
else:
    执行语句4

Translated into natural language is:

If judgment condition 1 is true, execute statement 1, otherwise, execute statement 2; if judgment condition 2 is true, execute statement 2, otherwise, execute statement 3; if judgment condition 3 is true, execute statement 3. Otherwise, statement 4 is executed.

When making multiple condition judgments, else can also be omitted. Because whether in the ordinary if statement structure or in this multi-condition judgment, else represents the "other" situation. If you don't want to execute any statement for the "other" situation, you can omit it.

 

 

There are many application scenarios for multi-condition judgment, and the last project we will do is an example of multi-condition judgment. Now let's use a simple example to illustrate.

In [10]: a = 3.5
         if a < 0:
             print("a为负数。")
         elif a % 2 == 0:
             print("a为偶数。")
         elif a % 2 == 1:
             print("a为奇数。")
         else:
             print("a不是正整数。")
Out[10]: a不是正整数。

3. Statement nesting

In addition to using elif to implement multi-condition judgments, multiple if statements can also be nested to implement multi-condition judgments. Although it is called statement nesting, it does not have to be understood as a sophisticated technology, but the execution statement under a certain judgment condition is itself an if statement structure. With this understanding, it will be more convenient for everyone to use in the future, without having to think about how to nest.

if 判断条件1:
    执行语句1
elif 判断条件2:
    执行语句2
        if 判断条件2-1:
            执行语句2-1
        elif 判断条件2-2:
            执行语句2-2
        else:
            执行语句2-3
else:
    执行语句3

Although the structure of the above statement looks a bit complicated, it is derived from the basic structure of the if statement. You can try to translate it into natural language. If there is no problem, then it means that you have fully grasped the meaning of the if statement.

Finally, let's express the above example in a nested manner. Please pay attention to the difference.

In [11]: a = 3.5
         if a < 0:
             print("a为负数")
         elif a > 0:
             if a % 2 == 0:
                 print("a为偶数。")
             elif a % 2 == 1:
                 print("a为奇数。")
             else:
                 print("a不是正整数")
         else:
             print("a为0。")
Out[11]: a不是正整数

4. Syntax format:

Having mastered the meaning of the if statement, the rest is the format requirements.

Because what we learned before was a single line of code, there were not too many format requirements. But when it comes to control flow statements, it is different. They have strict symbol, format and indentation requirements, otherwise an error will be reported. But it is very simple to say, just pay attention to two points.

One is that there must be a ":" (note the English colon) after each keyword sentence, which is the sentence line where if, elif, and else are located.

Second, the execution statement after each colon must be indented, representing the next level of statement. Generally, you can use the Tab key to indent directly. Software such as Jupyter Notebook and PyCharm will also enter ":" and press Enter to automatically complete the indentation. If in the case of statement nesting, etc., there is a multi-level statement structure, then it must be indented again at the indentation position of the previous level, and the program can generally be realized automatically.

This format requirement and display mode is exactly the embodiment of Python language friendliness. The hierarchical structure of the sentence is clear at a glance through indentation, which is very easy to read. The implementation method is also very simple, and it can be done in one click.

5. Ternary operation

In the article "Learning Python with You Hand in Hand" 13-Operation , we mentioned the ternary operation, because the if statement was not introduced at that time, so this part of the content was omitted. Now, with the above foundation, we can understand the ternary operation.

The ternary operation is actually a simplified if...else... statement structure, as long as the entire statement is written on the same line, there is no difference in semantics, and there are no format requirements such as ":" and indentation. The only thing to note is that the ternary operation is an operation, the result of which is to be assigned to a variable, and this value is calculated through the if...else... statement structure and the expression in it.

The ternary operation can be represented by the following structure:

a = expression 1 if judgment condition else expression 2

Translated into natural language is:

If the judgment condition is true, the value of a is equal to the result of expression 1, otherwise the value of a is equal to the result of expression 2.

In [12]: a = 2
         b = "奇数" if a % 2 == 1 else "偶数"   # 这里的表达式是字符串
         print("a是{}。".format(b))
Out[12]: a是偶数。
​
In [13]: a = 2
         b = a * 2 if a < 2 == 1 else a ** 2   # 这里的表达式是算数运算
         print(b)
Out[13]: 4

The above is the knowledge points about the judgment statement if, and we will write an example below, using the judgment statement if and the knowledge we have learned before. Now, you can close Jupyter Notebook first, and we will use PyCharm to write this program.

Today, the example we are going to write is the "rock, paper, scissors" game that we are very familiar with. The entire process of the game is the complete information flow execution process that we talked about in the previous article, first interactive input, then program processing, and finally output results.

The input part is the content of the punch input by the user of the program, rock, scissors or cloth.

The program processing includes two parts, one is that the computer randomly punches, and the other is that the computer judges the outcome according to the rules of the game.

The output part is the outcome of the game.

Below, the entire program text and PyCharm screenshots are shown to you, in which the explanation of the program statements is explained using comments.

In [14]: import random   # 因为要使用随机函数,需要先导入随机函数库
 
         # 交互式输入过程,使用input()函数
         user = input("请输入您要出的拳(石头、剪刀、布):")
         
         # 使用choice()函数,实现在序列中随机选取一个元素,做为电脑出的拳
         computer = random.choice(['石头', '剪刀', '布'])
         
         # 以下是程序处理过程,直接按照游戏规则进行判断,根据判断结果进行输出
         
         # 把所有游戏者赢的情况列举出来,任何一种情况出现,就输出游戏者胜利
         if (user == '石头' and computer == '剪刀') or (user == '剪刀' and computer == '布') or (user == '布' and computer == '石头'):
             print("您出的是:{},电脑出的是:{}。恭喜,您赢了!".format(user, computer))
             
         # 打平的情况最容易描述,所以作为一个判断条件
         elif user == computer:
             print("您出的是:{},电脑出的是:{}。打平了!".format(user, computer))
             
         # 其它情况就是游戏者输的情况,因为描述比较复杂,放在其它情况里,就不用写很复杂的判断条件了
         else:
             print("您出的是:{},电脑出的是:{}。很遗憾,您输了!".format(user, computer))
             
Out[14]: 请输入您要出的拳(石头、剪刀、布):布
​
Out[15]: 您出的是:布,电脑出的是:石头。恭喜,您赢了!

As you can see from the screenshot above, there is a comment (using triple quotation marks """) at the top of the program, which describes some basic information of the program. I suggest you do the same. First, you can record the program. Content, to avoid forgetting it in the future; second, through this record, you can see the course of learning Python. Some programs may also be written better and more concise as we learn more and more , These are the processes of our continuous growth.

In addition, there is a "\" at the end of the 20th line of the program. This symbol is an identifier used to wrap a longer line of code to continue input. If you don't write "\", it will be considered by the program as a new line of code. There may be errors in both format requirements and program content.

In the process of PyCharm inputting code, there will be many convenient hints. For example, used variables will be filled, and format errors or grammatical errors will have corresponding yellow or red wavy lines. You can move the mouse to the prompt and you will be able to see related suggestions or prompt content. PyCharm is not only powerful, but also excellent in many details, which is why I recommend you to use this software.

At this point, we have completed the first real Python program. You can play a few more and enjoy your learning results.

But in the process of the game, did everyone feel any inconvenience? For example, you have to run the program once every time to play, and if there is an error in the input process, it will report an error and interrupt.

These are indeed deficiencies in our version. But it doesn't matter, it's only the V1.0 version at present. In the following study, we will not only improve the shortcomings of this version, but also continue to enrich the functions of this game. Using the while() function that will be introduced in the next article, you can realize the continuous running of the game without us having to run it manually every time, so stay tuned.

 

 


Thanks for reading this article! If you have any questions, please leave a message and discuss together ^_^

Welcome to scan the QR code below, follow the "Yesu Python" public account, read other articles in the "Learning Python with You Hand in Hand" series, or click the link below to go directly.

"Learning Python with You Hand in Hand" 1-Why learn Python?

"Learning Python with you hand in hand" 2-Python installation

"Learning Python with You Hand in Hand" 3-PyCharm installation and configuration

"Learning Python with You Hand in Hand" 4-Hello World!

"Learning Python with You Hand in Hand" 5-Jupyter Notebook

"Learning Python with You Hand in Hand" 6-String Identification

"Learning Python with You Hand in Hand" 7-Index of Strings

"Learning Python with You Hand in Hand" 8-String Slicing

"Learning Python with You Hand in Hand" 9-String Operations

"Learning Python with You Hand in Hand" 10-String Functions

"Learning Python with You Hand in Hand" 11-Formatted Output of Strings

"Learning Python with You Hand in Hand" 12-Numbers

"Learning Python with You Hand in Hand" 13-Operation

"Learning Python with You Hand in Hand" 14-Interactive Input

For Fans: Follow the "also said Python" public account, reply "Hand 15", you can download the sample sentences used in this article for free.

Also talk about Python-a learning and sharing area for Python lovers

 

Guess you like

Origin blog.csdn.net/mnpy2019/article/details/98849910