Home > Backend Development > Python Tutorial > Python program branch structure example code analysis

Python program branch structure example code analysis

WBOY
Release: 2023-05-03 11:37:06
forward
1892 people have browsed it

Single branch structure: if statement

Python The syntax format of the if statement is as follows:

if

A statement block is a sequence of one or more statements executed after the if condition is met. The statements in the statement block are passed with The line if is indented to express the inclusion relationship. The if statement first evaluates the result value of the condition, and if the result is True, the sequence of statements in the statement block is executed, and control then passes to the next statement of the program. If the result is False, the statements in the statement block will be skipped.

if Whether the statement block in the statement is executed or not depends on conditional judgment. But no matter what the situation, control will go to the next statement at the same level after the if statement.

if The conditional part of the statement can use any statement or function that can produce True or False. The most common way to form judgment conditions is to use relational operators. Python The language has a total of 6 relational operators, including less than, less than or equal to, greater than or equal to, greater than, equal to, and not equal to.

Special attention, Pybon uses “=" to indicate assignment statements, and uses “==” to indicate equals.

Let’s use an example to better grasp the if statement.

Air pollution is a matter of great concern to society today, and PM2.5 is an important indicator to measure air pollution. PM2.5 refers to particulate matter in the atmosphere with a diameter less than or equal to 2.5 um that can enter the lungs. PM2.5 Particles are small in size, contain a large amount of toxic and harmful substances, stay in the atmosphere for a long time, and are transported over long distances. Therefore, they have a great impact on human health and the quality of the atmospheric environment. The current air quality level is classified as 6 based on the PM2.5 value. PM2.5 Values ​​between 0~35 are excellent air quality, 35~75 is good, 75~115 is light pollution , 115~150 is moderate pollution, 150~250 is severe pollution, 250~500 is severe pollution.

A simplified version of the air quality standard adopts a three-level model: 0~35 is excellent, 35~75 is good, 75 and above for pollution. People may not care about the specific PM2.5 index value, but are more concerned about the air quality. The computer can issue air quality alerts by PM2.5 index classification.

The IPO description of this issue is as follows:

Input: PM2.5 value that receives external input

Processing: &emsp ; if PM2.5 value≥ 275, print air pollution warning  if 35PM2.5 Value< 75, print air quality is good, moderate outdoor exercise is recommended  if PM2.5 value< 35, print air quality is excellent , it is recommended for outdoor sports

Output: Print air quality reminder

The specific code is as follows:

PM = eval(input("请输入 PM2.5 数值:"))

if 0 <= PM < 35:
    print("空气优质,快去户外运动")
if 35 <= PM < 75:
    print("空气良好,适度户外运动")
if 75 <= PM:
    print("空气污染,请小心!")
Copy after login

The above example shows an example of conditional comparison using numbers, characters or strings are also Can be used for conditional comparisons. String comparison is essentially a comparison of strings corresponding to Unicode encodings. Therefore, string comparisons are performed in dictionary order. For example, English uppercase characters have a smaller Unicode encoding than lowercase characters. Here are some examples:

print(4 < 5)
Copy after login

True

print("python" == "python")
Copy after login

True

print("Python" > "python")
Copy after login

False

Two-branch structure: if-else statement

Python The if-else statement is used to form a two-branch structure. The syntax format is as follows:

if :   
                                                                                                     ;Statement block 2>
Statement block
1

is a sequence of one or more statements executed after the
if

condition is met, statement block2 is the sequence of statements executed after if conditions are not met. The two-branch statement is used to distinguish two possibilities of conditions, namely True or

False

, which form the execution path respectively. We use the if-else statement to improve the code of the previous example:

PM = eval(input("请输入 PM2.5 数值:")) 

if PM >= 75:
    print("空气存在污染,请小心!")
else:
   print("空气没有污染,可以开展户外运动")
Copy after login

There is also a more concise expression of the two-branch structure, which is suitable for returning specific values ​​through judgment. Value, the syntax format is as follows:

if

else

Among them, the expression 1/2

is generally a value of numeric type or string type. At this time, the code can be changed to:
PM = eval(input("请输入 PM2.5 数值:"))

print("空气{}污染!".format("存在" if PM >= 75 else "没有"))
Copy after login

if-else 的紧凑结构非常适合对特殊值处理的情况,其他例子如下:

count = 2
print(count if count != 0 else "不存在")
Copy after login

2

count = 0
print(coutn if count != 0 else "不存在")
Copy after login

不存在

多分支结构:if-elif-else 语句

Pythonif-elif-else 描述多分支结构,语句格式如下:

if <条件1>:
  <语句块 1>
elif <条件2>:
  <语句块 2>
else:
  <语句块 N>

多分支结构是二分支结构的扩展,这种形式通常用于设置同一个判断条件的多条执行路径。

Python 依次评估寻找第一个结果为 True 的条件,执行该条件下的语句块,结束后跳过整个 if-elif-else 结构,执行后面的语句。如果没有任何条件成立,else 下面的语句块将被执行。else子句是可选的。

前面的例子通过多条独立的 if 语句对同一个变量 PM 进行判断,这种情况更适合多分支结构,改进后的代码如下:

PM = eval(input("请输入 PM2.5 数值:"))

if 0 <= PM < 35:
    print("空气优质,快去户外运动!")
elif 35 <= PM < 75:
    print("空气良好,适度户外运动")
else:
    print("空气污染,请小心!")
Copy after login

The above is the detailed content of Python program branch structure example code analysis. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template