当前位置:网站首页>3.1 simple condition judgment
3.1 simple condition judgment
2022-06-27 15:52:00 【leeshuqing】
Here is an important program control statement : Conditional statements .
up to now , What we learned Python They are organized one sentence after another , The code is also executed in writing order , This method of organizing code statements can be called sequential statements .

And the so-called control statement , It refers to some code organization methods that change the traditional sequential execution method , For example, sometimes we hope that some statements will not be executed , It is even allowed to be executed multiple times when conditions permit . Specifically, it includes conditional judgment statements and loop statements , Practice and theory have proved , With the help of sequential statements 、 Conditional judgment statements and loop statements , We can express any operational logic and application functions that can be expressed .
Code is executed one by one according to the sequence of statements . But sometimes , We need a more flexible way of executing code . For example, in data analysis , We often have to choose different processing methods according to the type of data , The processing code does not have to be completely executed each time it is run , Instead, it is carried out selectively . This is the meaning of conditional judgment . Conditional judgment gives us the ability to choose to execute code , Make different code executed under different conditions . It's like a train passing by a railway , Sometimes this way , Sometimes go that way , But only one way at a time .

We explain it through an example , Let's see how to realize conditional judgment .
Here is the final exercise to complete , The average score of all students in a class shall be determined by five grades , For example, according to 90、80、70、60 Four points , They are classified as excellent 、 good 、 in 、 There are five grades for passing and failing .
In order to enable everyone to get started , Let's start with the simplest example . For example, allow users to enter a score , Judge whether you pass or not .
grade = int(input())
The input is simple , It's used here grade Variables store this score .
How to judge ? stay Python In language , Can pass if With this statement ,if If means , think about it , If the next program is written in Chinese characters , Should be :

Programming is actually computerizing our ideas for solving problems , As long as you clear your mind , It can be re expressed in the format understood by the computer . For example, all the above ideas are written as Python The code is :
grade = int(input())
if grade >= 60:
print(' pass ')
if grade < 60:
print(' fail, ')
At this time, if the input is greater than or equal to 60 Integral number of fractions , Will be output “ pass ”, Less than 60 Points will be output “ fail, ”.
because Python Languages are case sensitive , So please don't capitalize at will .if If the latter is the condition , For example, greater than or equal to 60 branch , Pay attention to the writing of greater than or equal to , Also pay attention to the following expression of less than . No matter how the condition is written , There are only two results , One is right , be appointed after a period as acting , One is wrong , I.e. false , So the result of the condition will produce a Boolean value . If it's right , Just execute the contents in the following statement block . Finally, don't forget , The required colon must be used as the end of the condition .

ad locum ,Python Code indentation is used to represent the statements to be executed after the conditions are met , You can use multiple spaces for specific indents ( Generally in PyCharm In Chinese, it means 4 individual ) perhaps Tab. therefore , We are writing something else Python Code , Don't indent your code easily , Otherwise, unexpected indentation will occur (unexpected indent) Error of , such as :

meanwhile , Where indentation is required, the indentation cannot be omitted , The error prompt is that an indent is required :

But think about it , If a grade has been judged to be passed , Whether it is necessary to judge again whether it is less than 60 branch ? Obviously there is no need . in fact , These two conditions are complementary , under these circumstances , We can write the idea as :

The corresponding code can be written as :
grade = int(input())
if grade >= 60:
print(' pass ')
else:
print(' fail, ')
This else It can be understood as “ otherwise ” It means . It's easier , And it's more efficient , once if The conditions are met , After the execution of the corresponding statement block, the output passes , No more unnecessary judgments .
Again, please note else The last necessary colon . You may think that these colons seem useless , In fact, it is mainly used to split conditions and corresponding execution statements , For example, it can be written in the following form :
grade = int(input())
if grade >= 60: print(' pass ')
else: print(' fail, ')The code functions the same , At this point, the colon has a very obvious function of segmentation . It is even possible to adopt a method that if Statements are placed in the middle of other statements to achieve the same effect :
grade = int(input())
print(' pass ' if grade >= 60 else ' fail, ')The code function remains the same , It is equivalent to combining the judgment and the output , You can write other similar sentences . Of course, we do not recommend that beginners write like this , Necessary line breaks often enhance the readability of the code .
Again, emphasize the use of code indentation . Let's take a look at an exercise :
grade = int(input())
if grade >= 60:
print(' pass ')
print('!')
else:
print(' fail, ')
When we type in 61 when , You will find that the output has “ pass ” and “!” Two content . The reason is that when grade Greater than or equal to 60 when , The following indented statements will be executed .
If... Will be output at this time “!” Delete indents and write in the top space :
grade = int(input())
if grade >= 60:
print(' pass ')
print('!')
else:
print(' fail, ')
The code will report an error , Errors are invalid syntax (invalid syntax), The reason is that the head started “!” The output statement represents the above if The statement has ended , So this statement and if Statements are executed in parallel order . This is really no problem , But the following else There will be no corresponding if And make mistakes . therefore , Although indentation is a statement that outputs an exclamation point , But what really makes a mistake is the following else, This requires us to look at the overall situation when troubleshooting errors, so as to accurately understand the place and cause of errors .
Supporting learning resources 、 MOOC video :
Python Big data analysis - Shu Qing Li
https://www.njcie.com/python/
边栏推荐
猜你喜欢

CNN convolutional neural network (the easiest to understand version in History)

sql注入原理
![Beginner level Luogu 1 [sequence structure] problem list solution](/img/60/5e151ba31eb00374c73be52e3bfa7e.png)
Beginner level Luogu 1 [sequence structure] problem list solution

VS编译遇到的问题

Teach you how to package and release the mofish Library
![Luogu_ P1003 [noip2011 improvement group] carpet laying_ Violence enumeration](/img/65/413ac967cc8fc22f170c8c7ddaa106.png)
Luogu_ P1003 [noip2011 improvement group] carpet laying_ Violence enumeration

2022-2-16 learning the imitated Niuke project - Section 6 adding comments

Sigkdd22 | graph generalization framework of graph neural network under the paradigm of "pre training, prompting and fine tuning"

PSS:你距离NMS-free+提点只有两个卷积层 | 2021论文

PSS: you are only two convolution layers away from the NMS free+ point | 2021 paper
随机推荐
Openssf security plan: SBOM will drive software supply chain security
16 -- 删除无效的括号
洛谷_P1002 [NOIP2002 普及组] 过河卒_dp
Let's talk about the process of ES Indexing Documents
CNN convolutional neural network (the easiest to understand version in History)
创建数据库并使用
Atomic operation class
FPGA based analog I ² C protocol system design (with main code)
On traversal of tree nodes
SQL parsing practice of Pisa proxy
Why can't the start method be called repeatedly? But the run method can?
The role of the symbol @ in MySQL
Design principles and ideas: design principles
关于TensorFlow使用GPU加速
Admixture usage document Cookbook
PSS: you are only two convolution layers away from the NMS free+ point | 2021 paper
【kotlin】第二天
E modulenotfounderror: no module named 'psychopg2' (resolved)
A distribution fission activity is more than just a circle of friends!
#27ES6的数值扩展