当前位置:网站首页>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/
边栏推荐
- Design of CAN bus controller based on FPGA (with main codes)
- E modulenotfounderror: no module named 'psychopg2' (resolved)
- Luogu_ P1003 [noip2011 improvement group] carpet laying_ Violence enumeration
- 洛谷_P1008 [NOIP1998 普及组] 三连击_枚举
- Design of direct spread spectrum communication system based on FPGA (with main code)
- Pisa-Proxy 之 SQL 解析实践
- 专家:让你低分上好校的都是诈骗
- Talk about redis transactions
- Indexeddb learning materials
- Cesium uses mediastreamrecorder or mediarecorder to record screen and download video, as well as turn on camera recording. [transfer]
猜你喜欢

Pisa-Proxy 之 SQL 解析实践
![[high concurrency] deeply analyze the callable interface](/img/24/33c3011752c8f04937ad68d85d4ece.jpg)
[high concurrency] deeply analyze the callable interface
![洛谷_P1003 [NOIP2011 提高组] 铺地毯_暴力枚举](/img/65/413ac967cc8fc22f170c8c7ddaa106.png)
洛谷_P1003 [NOIP2011 提高组] 铺地毯_暴力枚举

Talk about redis transactions

关于TensorFlow使用GPU加速

A distribution fission activity is more than just a circle of friends!

E ModuleNotFoundError: No module named ‘psycopg2‘(已解决)

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

The latest development course of grain college in 2022: 8 - foreground login function

Sigkdd22 | graph generalization framework of graph neural network under the paradigm of "pre training, prompting and fine tuning"
随机推荐
Design principles and ideas: design principles
Does polardb-x open source support mysql5.7?
Piblup test report 1- pedigree based animal model
16 -- remove invalid parentheses
Design of spread spectrum communication system based on FPGA (with main code)
手机号码的格式
LeetCode每日一练(主要元素)
AbortController的使用
A distribution fission activity is more than just a circle of friends!
E modulenotfounderror: no module named 'psychopg2' (resolved)
Distributed session solution
Teach you how to realize pynq-z2 bar code recognition
Weekly snapshot of substrate technology 20220411
[issue 17] golang's one-year experience in developing Meitu
PSS: you are only two convolution layers away from the NMS free+ point | 2021 paper
sql注入原理
Does polardb-x currently not support self-made database service Das?
事务的四大特性
Luogu_ P1002 [noip2002 popularization group] crossing the river_ dp
[MySQL] query valid data based on time