I. Introduction
1. A brief introduction to the control structure
Control structures are statements in a programming language that control the flow of program execution. They are divided into two main categories:
- Conditional statements :
if
Statement: Execute a block of code based on conditions.elif
Statement: If the previous condition does not hold, try this condition.else
Statement: This block of code is executed if all conditions are not met.
- loop statement :
for
Loop: iterate through each element in the sequence.while
Loops: Repeat a block of code as long as a condition is true.
2. The importance of control structures in programming
The importance of control structures in programming is that they enable a program to execute specific blocks of code based on different conditions or repeatedly. This enables programs to make decisions, perform repetitive tasks, and manage complex processes to implement a variety of functions and algorithms.
- Decision-making ability : Through conditional statements (such as if, elif, else), the program can execute different code paths according to different conditions, thereby realizing the decision-making function.
- Repeated execution : Loop statements (such as for, while) allow the program to repeatedly execute blocks of code, which is crucial for handling repetitive tasks, traversing data structures, and other scenarios.
- Process management : The control structure can effectively manage the execution process of the program, so that the program can be executed in a logical sequence, improving the readability and maintainability of the code.
- Algorithm implementation : The control structure is the basis for algorithm implementation. Algorithms such as sorting, search, and dynamic programming are inseparable from the support of conditional statements and loop statements.
- Flexibility and scalability : Rational use of control structures can make the program more flexible and scalable, able to adapt to different inputs and scenarios, and improve the versatility of the program.
In summary, control structures are a core component of programming languages, and mastering them is crucial to writing feature-rich and logically complex programs.
2. Conditional statements
1. Basic use of if statement
In Python, if
statements are used to execute blocks of code based on conditions. The following is if
the basic usage of statements:
-
Single conditional
if
statement :if condition: # 如果条件为真,则执行这里的代码 print("条件为真,执行此代码块。")
-
Multiple conditional
if
statements :if condition1: # 如果条件1为真,则执行这里的代码 print("条件1为真,执行此代码块。") elif condition2: # 如果条件1不为真,但条件2为真,则执行这里的代码 print("条件1不为真,条件2为真,执行此代码块。") else: # 如果条件1和条件2都不为真,则执行这里的代码 print("条件1和条件2都不为真,执行此代码块。")
-
if
Code block in statement :if
A colon ( ) after a statement:
marks the beginning of a code block.- Code blocks should be indented (usually 4 spaces or 1 tab).
- Correct indentation is key to control structures in Python.
-
Precautions :
- Conditional expressions should be surrounded by parentheses, especially in the case of multiple conditions.
- Don't forget
if
to add a colon after the statement. - Make sure your code blocks are indented correctly.
-
Example :
age = 20 if age >= 18: print("您已成年。") else: print("您还未成年。")
In this example, if age
the variable is greater than or equal to 18, print out "You are an adult."; otherwise, print out "You are not yet a minor.". Remember, if
the basic purpose of a statement is to decide whether to execute a specific block of code based on the result of a conditional evaluation.
2. Use of else clause
In Python, else
clauses are often if
used together with statements to provide if
alternative execution paths when a condition is not met. Here are else
the basic uses of clauses:
-
Clauses
if
after simpleelse
statements :if condition: # 如果条件为真,则执行这里的代码 else: # 如果条件不为真,则执行这里的代码 print("条件不为真,执行此代码块。")
-
elif
Clauses andelse
clauses :if condition1: # 如果条件1为真,则执行这里的代码 elif condition2: # 如果条件1不为真,但条件2为真,则执行这里的代码 else: # 如果条件1和条件2都不为真,则执行这里的代码 print("条件1和条件2都不为真,执行此代码块。")
-
else
Clause ANDfor
orwhile
Loop :for item in collection: # 循环体代码 else: # 当循环正常完成时执行,即循环体未被`break`语句打断时执行 print("循环体已全部执行完毕。")
When using else
clauses, you need to pay attention to the following points:
else
Clauses mustif
be used with and after theif
statement.else
Code blocks within clauses should have the same indentation level to keep the code structure clear.- Within
elif
a clause, eachelif
and the correspondingelse
must have the same indentation level. - In an
for
orwhile
loop,else
the clause is executed at the normal end of the loop, that is,break
when the body of the loop is not interrupted by a statement. For example:
x = 10
if x > 0:
print("x 是正数")
else:
print("x 不是正数")
In this example, if x
it is greater than 0, print "x is a positive number"; otherwise, print "x is not a positive number".
3. Use of elif clause
In Python, elif
the (short for else if) clause is used to if
provide additional condition checks when the condition of the statement is not met. elif
Clauses are often used to implement multi-conditional branch logic. Here are elif
the basic uses of clauses:
-
if-elif-else
structure :if condition1: # 如果条件1为真,则执行这里的代码 elif condition2: # 如果条件1不为真,但条件2为真,则执行这里的代码 else: # 如果条件1和条件2都不为真,则执行这里的代码 print("条件1和条件2都不为真,执行此代码块。")
-
elif
Order of clauses :elif
Clauses should be ordered from most likely to least likely.- This allows the program to find clauses that satisfy the condition faster
elif
and execute them.
-
Precautions :
- Each
elif
and the correspondingelse
must have the same indentation level. - If the first
if
condition is not met, Python will check the firstelif
condition and execute the corresponding code block if it is met. - If all the
if
ANDelif
conditions are not met,else
the clause (if any) is executed.
- Each
-
Example :
grade = 'B' if grade == 'A': print("优秀!") elif grade == 'B': print("良好。") elif grade == 'C': print("及格。") else: print("加油,再努力!")
In this example, depending on grade
the value of the variable, the program prints different messages. If grade
it is 'A', print "Excellent!"; if it is 'B', print "Good."; if it is 'C', print "Pass."; if neither, print "Come on, try harder." ! ". elif
Clauses are a common way to implement complex conditional judgments. They make the code clearer and easier to understand.
4. Nested if statements
Nested if
statements refer to using another statement if
inside a statement block . if
Nested if
statements allow you to execute different code paths based on multiple conditions. The following is if
the basic usage of nested statements:
- Nested
if
statements :x = 10 if x > 0: print("x 是正数") if x < 100: print("x 是一个小于100的正数") else: print("x 不是正数")
In this example, first check x
if it is greater than 0. If it is, then further check x
if it is less than 100. 2. Notes :
- Make sure the inner
if
statements have theif
same indentation level as the outer statements. - Each nested
if
statement must have an explicit condition to avoid infinite loops.
- Example :
age = 21 if age >= 18: print("您已成年。") if age >= 21: print("您已超过法定饮酒年龄。") else: print("您还未达到法定饮酒年龄。") else: print("您还未成年。")
In this example, first check age
whether it is greater than or equal to 18, and if so, then further check whether it is greater than or equal to 21. Nested if
statements are very useful when dealing with complex logic, but overuse or incorrect use can lead to code that is difficult to understand and maintain. So when writing nested if
statements, make sure your logic is clear and keep it as concise as possible.
3. Logical operators
1. Use of and
, or
and not
operators
In Python, and
the , or
and not
operators are used for logical operations. They are used to combine multiple conditions or negate a single condition.
and
operator
and
The result of the operator is true if both conditions are true .- Otherwise, the result is false.
condition1 = True
condition2 = False
result = condition1 and condition2
print(result) # 输出:False
or
operator
or
The result of the operator is true if at least one of the two conditions is true .- Otherwise, the result is false.
condition1 = True
condition2 = False
result = condition1 or condition2
print(result) # 输出:True
not
operator
- Negate a single condition.
- If the condition is true,
not
the result of the operator is false. - Otherwise, the result is true.
condition = True
result = not condition
print(result) # 输出:False
Precautions
- The operands on both sides of logical operators are usually Boolean values.
- The order of operation of logical operators is from left to right.
- Logical operators can be used with any Boolean expression.
Example
# 组合使用 and、or 和 not 运算符
x = 10
y = 20
result = (x > 5) and (y > 10)
print(result) # 输出:False
result = (x > 5) or (y > 10)
print(result) # 输出:True
result = not (x == y)
print(result) # 输出:True
These operators are very useful when writing conditional statements, and they can help you build complex logical judgments. Proper use of logical operators can improve the clarity and readability of your code.
2. Application in conditional statements
Logical operators are widely used in conditional statements, and they allow you to combine multiple conditions to make more complex decisions. In Python, the main logical operators include and
, or
and not
.
and
operator
and
Operators are used to check whether two or more conditions are true at the same time.- Within
if
a statement, you canand
combine multiple conditions using.
x = 10
y = 20
if x > 5 and y > 10:
print("x 和 y 都大于它们的阈值。")
In this example, the code block will only be executed if it x
is greater than 5 and y
greater than 10.
or
operator
or
Operators are used to check whether at least one of two or more conditions is true.- Within
if
a statement, you canor
provide an alternative condition using .
x = 10
y = 5
if x > 5 or y > 10:
print("x 或 y 至少有一个大于它们的阈值。")
In this example, x
if it is greater than 5 or y
greater than 10, the code block will be executed.
not
operator
not
Operator is used to negate a single condition.- Within
if
a statement, you can usenot
to reverse the logic of a condition.
x = 5
if not (x > 10):
print("x 不大于10。")
In this example, not
the operator is used to check x
if it is not greater than 10. If x
it is not greater than 10, the code block will be executed.
Precautions
- When using logical operators, be careful to keep the code readable and use spaces and newlines appropriately.
- The operands on both sides of a logical operator should be of the same data type, usually Boolean.
- When using multiple logical operators in combination, pay attention to the priority of the operation,
and
which has a higher priority thanor
. By rationally using logical operators, conditional statements can be made more precise and powerful, and can handle more complex logical judgments.
4. Loop structure
1. for
Basic use of loops
In Python, for
a loop is an iteration statement that traverses a sequence (such as a list, tuple, string) or any iterable object. Here are for
the basics of using loops:
-
Basic
for
loop :for item in iterable: # 遍历iterable中的每个item print(item)
-
for
Iteration variables in loops :- Iteration variables are usually named
item
, but you can use any valid variable name. - On each iteration, the next element in
item
is assigned .iterable
- Iteration variables are usually named
-
for
Code block in loop :- Code blocks should be indented (usually 4 spaces or 1 tab).
- Correct indentation is key to control structures in Python.
-
Example :
# 遍历列表中的每个元素 fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)
In this example, for
the loop iterates over fruits
each element in the list and prints it. 5. Clauses for
in the loopelse
:
for
Loops can also contain an optionalelse
clause that is executed on each iteration of the outer loop without beingbreak
interrupted by a statement.else
clause is typically used to perform cleanup work or some code when the loop completes normally.
for item in iterable:
# 循环体代码
else:
# 当循环正常完成时执行
print("循环体已全部执行完毕。")
for
Loops are a very powerful feature in Python and are widely used in scenarios such as data processing and file operations. Loops for
allow you to easily iterate and manipulate each element in a sequence.
2. while
Basic use of loops
In Python, while
a loop is a cyclic structure that repeatedly executes a block of code based on a specific condition. Here are while
the basics of using loops:
-
Basic
while
loop :while condition: # 当condition为真时,重复执行这里的代码 print("条件为真,继续循环。")
-
The basic structure of a loop :
while
The keyword marks the beginning of the loop.- Conditional expressions should be surrounded by parentheses.
- Code blocks should be indented (usually 4 spaces or 1 tab).
-
Conditional judgment :
- The loop will continue until the condition is no longer true.
- The condition is usually a Boolean expression that determines whether the loop continues execution.
-
Example :
count = 0 while count < 5: print(count) count += 1
In this example, while
the loop repeats until count
the variable reaches the value 5. 5. Notes :
- Avoid infinite loops and ensure that the condition will eventually become false.
- Indent code blocks correctly to keep your code readable.
while
Loops are an important tool for implementing repetitive tasks and continuously checking conditions. It is often used to handle situations that require multiple iterations until a certain condition is met. Proper usewhile
of loops can improve the efficiency and maintainability of your program.
5. Loop control statements
1. break
Use of statements
In Python, break
a statement is used to immediately exit the loop structure you are currently in, whether it is for
a loop or while
a loop. The following is break
the basic usage of statements:
for
Used in a loopbreak
:for item in iterable: if item == "special": break # 退出for循环 print(item)
In this example, if the statement in the loop item
equals "special", break
it will cause the loop to terminate immediately. 2. Use in a loopwhile
break
:
count = 0
while count < 5:
print(count)
count += 1
if count == 3:
break # 退出while循环
In this example, when count
equal to 3, break
the statement will cause while
the loop to terminate immediately. 3. Notes :
break
A statement can only be used at the loop level in which it is located.- Once the statement is executed
break
, the loop structure will end immediately, and the remaining code in the loop body will no longer be executed. - When using it
break
, you should ensure that the loop will eventually end to avoid creating an infinite loop.break
Statements are one of the key ways to control loop execution, allowing you to exit the loop early when certain conditions are met, thereby avoiding unnecessary iterations. Correct usebreak
can make your code more efficient and flexible.
2. continue
Use of statements
In Python, continue
statement is used to skip the remaining code of the current loop and start the next iteration. When continue
the statement executes, the current loop iteration terminates immediately, program control flow jumps back to the beginning of the loop, the loop condition is checked, and if the condition is true, the next iteration begins. The following is continue
the basic usage of statements:
for
Used in a loopcontinue
:for item in iterable: if item == "special": continue # 跳过当前迭代,继续下一次迭代 print(item)
In this example, if item
equals "special" in the loop, continue
the statement will cause the current iteration to terminate immediately and start the next iteration. 2.Use in while
a loopcontinue
:
count = 0
while count < 5:
count += 1
if count == 3:
continue # 跳过当前迭代,继续下一次迭代
print(count)
In this example, when count
equal to 3, continue
the statement will cause the current iteration to terminate immediately and start the next iteration. 3. Notes :
continue
A statement can only be used at the loop level in which it is located.- When used
continue
, you should make sure that it does not cause the loop to end prematurely, unless this is the desired effect. continue
Statements are typically used to skip unnecessary iterations, or to perform actions within a loop under certain conditions.continue
Statements are another way to control loop execution, allowing you to skip the current iteration when certain conditions are met, thereby improving the efficiency and accuracy of the loop. Proper usecontinue
can make your code more flexible and easier to maintain.
3. Use of pass statement
In Python, pass
a statement is a no-op that performs no action and is typically used as a placeholder or to maintain the integrity of the code structure. Use when your code requires a statement, but you don't want it to perform any actual action pass
. The following is pass
the basic usage of statements:
-
Basic
pass
statement :pass # 这是一个空操作,不执行任何操作
-
Use in function definition
pass
:def example_function(): pass # 函数中使用pass作为占位符
In this example, example_function
it is an empty function, which does not contain any actual code. 3. Use in class definitionpass
:
class ExampleClass:
pass # 类中使用pass作为占位符
In this example, ExampleClass
it is an empty class, which does not define any properties or methods. 4. Notes :
pass
Statements are often used to keep the structure of your code intact, especially where a statement is expected but you don't want to perform any action.- Using it as a placeholder in a function or class
pass
ensures that your code follows Python's syntax rules, even if the function or class does not implement any functionality for the time being.pass
Although the statement is a no-op, in some cases it is necessary to keep the code clear and consistent. Correct usepass
can make the code cleaner and facilitate future code maintenance and expansion.
6. Exercises and Examples
Practice questions on conditional statements and loop structures
- Age judgment : Write a program to judge whether a person can vote based on the entered age (assuming the voting age is 18 years old).
age = int(input("请输入年龄:"))
if age >= 18:
print("可以投票。")
else:
print("还未到投票年龄。")
- Print a triangle : Use
for
a loop to print a right triangle.
for i in range(1, 6):
for j in range(1, i + 1):
print("*", end=" ")
print()
- Number-guessing game : Write a number-guessing game. The program randomly generates an integer between 1 and 100. The player has 10 chances to guess the number.
import random
secret_number = random.randint(1, 100)
for attempt in range(10):
guess = int(input("请猜一个1到100之间的整数:"))
if guess < secret_number:
print("太小了!")
elif guess > secret_number:
print("太大了!")
else:
print(f"恭喜你,猜对了!秘密数字是 {secret_number}。")
break
if attempt == 9:
print("你没有足够的尝试次数来猜出数字。")
Examples of real-world problem solving
Question 1: Calculate personal income tax
Assume that personal income tax is calculated as follows:
- If your monthly income is less than or equal to 5,000 yuan, you do not need to pay personal income tax.
- If the monthly income is between 5,000 yuan and 15,000 yuan, the tax rate is 5%.
- If the monthly income is between 15,000 yuan and 30,000 yuan, the tax rate is 10%.
- If the monthly income exceeds 30,000 yuan, the tax rate is 20%.
income = float(input("请输入您的月收入:"))
if income <= 5000:
tax = 0
elif income <= 15000:
tax = income * 0.05
elif income <= 30000:
tax = income * 0.10
else:
tax = income * 0.20
print(f"您的个人所得税为:{tax:.2f}元。")
Question 2: Calculate the sum of all even numbers between 1 and 100
sum_even = 0
for i in range(1, 101):
if i % 2 == 0:
sum_even += i
print(f"1到100之间所有偶数的和是:{sum_even}")
Linus took matters into his own hands to prevent kernel developers from replacing tabs with spaces. His father is one of the few leaders who can write code, his second son is the director of the open source technology department, and his youngest son is a core contributor to open source. Huawei: It took 1 year to convert 5,000 commonly used mobile applications Comprehensive migration to Hongmeng Java is the language most prone to third-party vulnerabilities. Wang Chenglu, the father of Hongmeng: open source Hongmeng is the only architectural innovation in the field of basic software in China. Ma Huateng and Zhou Hongyi shake hands to "remove grudges." Former Microsoft developer: Windows 11 performance is "ridiculously bad " " Although what Laoxiangji is open source is not the code, the reasons behind it are very heartwarming. Meta Llama 3 is officially released. Google announces a large-scale restructuringThis article is a reprint of the article Heng Xiaopai , and the copyright belongs to the original author. It is recommended to visit the original text. To reprint this article, please contact the original author.