Python program branch structure example code analysis
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 35 ≤ PM2.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("空气污染,请小心!")
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)
True
print("python" == "python")
True
print("Python" > "python")
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:
ifif
is a sequence of one or more statements executed after the:
;Statement block 2>
Statement block
1
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("空气没有污染,可以开展户外运动")
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
elseis generally a value of numeric type or string type. At this time, the code can be changed to:
Among them, the expression 1/2
PM = eval(input("请输入 PM2.5 数值:")) print("空气{}污染!".format("存在" if PM >= 75 else "没有"))
if-else 的紧凑结构非常适合对特殊值处理的情况,其他例子如下:
count = 2 print(count if count != 0 else "不存在")
2
count = 0 print(coutn if count != 0 else "不存在")
不存在
多分支结构:if-elif-else 语句
Python 的 if-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("空气污染,请小心!")
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

The article introduces the operation of MySQL database. First, you need to install a MySQL client, such as MySQLWorkbench or command line client. 1. Use the mysql-uroot-p command to connect to the server and log in with the root account password; 2. Use CREATEDATABASE to create a database, and USE select a database; 3. Use CREATETABLE to create a table, define fields and data types; 4. Use INSERTINTO to insert data, query data, update data by UPDATE, and delete data by DELETE. Only by mastering these steps, learning to deal with common problems and optimizing database performance can you use MySQL efficiently.

MySQL download file is corrupt, what should I do? Alas, if you download MySQL, you can encounter file corruption. It’s really not easy these days! This article will talk about how to solve this problem so that everyone can avoid detours. After reading it, you can not only repair the damaged MySQL installation package, but also have a deeper understanding of the download and installation process to avoid getting stuck in the future. Let’s first talk about why downloading files is damaged. There are many reasons for this. Network problems are the culprit. Interruption in the download process and instability in the network may lead to file corruption. There is also the problem with the download source itself. The server file itself is broken, and of course it is also broken when you download it. In addition, excessive "passionate" scanning of some antivirus software may also cause file corruption. Diagnostic problem: Determine if the file is really corrupt

The main reasons for MySQL installation failure are: 1. Permission issues, you need to run as an administrator or use the sudo command; 2. Dependencies are missing, and you need to install relevant development packages; 3. Port conflicts, you need to close the program that occupies port 3306 or modify the configuration file; 4. The installation package is corrupt, you need to download and verify the integrity; 5. The environment variable is incorrectly configured, and the environment variables must be correctly configured according to the operating system. Solve these problems and carefully check each step to successfully install MySQL.

MySQL refused to start? Don’t panic, let’s check it out! Many friends found that the service could not be started after installing MySQL, and they were so anxious! Don’t worry, this article will take you to deal with it calmly and find out the mastermind behind it! After reading it, you can not only solve this problem, but also improve your understanding of MySQL services and your ideas for troubleshooting problems, and become a more powerful database administrator! The MySQL service failed to start, and there are many reasons, ranging from simple configuration errors to complex system problems. Let’s start with the most common aspects. Basic knowledge: A brief description of the service startup process MySQL service startup. Simply put, the operating system loads MySQL-related files and then starts the MySQL daemon. This involves configuration

MySQL database performance optimization guide In resource-intensive applications, MySQL database plays a crucial role and is responsible for managing massive transactions. However, as the scale of application expands, database performance bottlenecks often become a constraint. This article will explore a series of effective MySQL performance optimization strategies to ensure that your application remains efficient and responsive under high loads. We will combine actual cases to explain in-depth key technologies such as indexing, query optimization, database design and caching. 1. Database architecture design and optimized database architecture is the cornerstone of MySQL performance optimization. Here are some core principles: Selecting the right data type and selecting the smallest data type that meets the needs can not only save storage space, but also improve data processing speed.

MySQL performance optimization needs to start from three aspects: installation configuration, indexing and query optimization, monitoring and tuning. 1. After installation, you need to adjust the my.cnf file according to the server configuration, such as the innodb_buffer_pool_size parameter, and close query_cache_size; 2. Create a suitable index to avoid excessive indexes, and optimize query statements, such as using the EXPLAIN command to analyze the execution plan; 3. Use MySQL's own monitoring tool (SHOWPROCESSLIST, SHOWSTATUS) to monitor the database health, and regularly back up and organize the database. Only by continuously optimizing these steps can the performance of MySQL database be improved.

MySQL can run without network connections for basic data storage and management. However, network connection is required for interaction with other systems, remote access, or using advanced features such as replication and clustering. Additionally, security measures (such as firewalls), performance optimization (choose the right network connection), and data backup are critical to connecting to the Internet.
