I. Overview of Conditional Statements
A program not only needs to execute code in sequence; it also needs to choose different execution paths based on different situations.
For example:
- The user logs in successfully and enters the system; if login fails, an error is displayed.
- If product inventory is sufficient, the order is allowed; if inventory is insufficient, an out-of-stock message is shown.
- If the user's age meets the requirement, registration is allowed; if not, registration is rejected.
- Different score ranges return different grades.
These scenarios all require conditional statements.
Python provides three main conditional branching keywords:
| Keyword | Purpose |
|---|---|
if |
Checks whether a condition is true and executes the corresponding code block when it is true |
elif |
When the previous condition is false, continues to check other conditions |
else |
When none of the previous conditions are true, executes the default branch |
The most basic structure:
if condition:
# Execute when the condition is true
statement
elif another_condition:
# Execute when the previous condition is false and the current condition is true
statement
else:
# Execute when all conditions are false
statement
Conditional statements are an important part of a program's control flow; they determine which execution path the program chooses while running.
II. The if Statement: Basic Conditional Judgment
1. Basic syntax of if
if is the most basic conditional judgment statement in Python.
Syntax:
if condition:
statement
Execution rules:
- Evaluate the
conditionexpression. - Perform a truth-value test on the result.
- If the result is true, execute the
ifcode block. - If the result is false, skip the code block and continue executing the following statements.
Example:
age = 20
if age >= 18:
print("已经成年")
Running result:
已经成年
Because the result of age >= 18 is True, the code inside the if is executed.
2. When the if condition is false
age = 16
if age >= 18:
print("已经成年")
print("程序继续执行")
Running result:
程序继续执行
When the condition is false, Python does not execute the if code block and instead continues directly with the statements after it.
3. The if condition can be an expression
A condition does not have to be a simple variable; it can also be a comparison expression, logical expression, or function call.
score = 85
if score >= 60:
print("考试通过")
Logical operators can also be used:
age = 25
has_permission = True
if age >= 18 and has_permission:
print("允许访问")
Membership operators can also be used:
role = "admin"
if role in {"admin", "operator"}:
print("拥有管理权限")
As long as an expression can produce a result that can be tested for truth value, it can be used as a condition.
4. An if code block can contain multiple statements
temperature = 35
if temperature > 30:
print("天气炎热")
print("建议减少户外活动")
print("注意补充水分")
When the condition is true, all statements indented in the same code block are executed.
III. Python Indentation and Code Blocks
1. Indentation determines the scope of a code block
Python uses indentation to indicate code blocks rather than braces {}.
For example:
age = 20
if age >= 18:
print("已经成年")
print("可以申请相关服务")
print("程序结束")
Here:
- The two indented statements belong to the
ifcode block. print("程序结束")does not belong to theifcode block.
2. Example of an indentation error
age = 20
if age >= 18:
print("已经成年")
At runtime, this raises an IndentationError because if requires an indented code block after it.
Correct way to write it:
age = 20
if age >= 18:
print("已经成年")
3. Different indentation levels represent different code blocks
age = 20
has_permission = True
if age >= 18:
print("年龄符合要求")
if has_permission:
print("拥有访问权限")
print("程序结束")
There are two levels here:
- Outer
if: checks the age. - Inner
if: checks the permission.
Python recommends using 4 spaces per indentation level.
4. Indentation and colons
if, elif, and else all need to be followed by a colon :.
if condition:
statement
elif another_condition:
statement
else:
statement
The colon indicates that a new code block begins after it.
IV. if-else: Two-branch structure
1. Basic syntax
When a program has only two possible execution outcomes, you can use if-else.
if condition:
statement_a
else:
statement_b
Execution rules:
- If the condition is true, execute the
ifcode block. - If the condition is false, execute the
elsecode block. - Only one of the two branches will be chosen for execution.
Example:
age = 16
if age >= 18:
print("允许进入")
else:
print("禁止进入")
Output:
禁止进入
2. Determining odd or even numbers
number = 7
if number % 2 == 0:
print("偶数")
else:
print("奇数")
Here, the modulo operator % is used to determine whether an integer has a remainder when divided by 2.
- If the remainder is 0, the number is even.
- If the remainder is not 0, the number is odd.
3. Checking login status
is_logged_in = False
if is_logged_in:
print("欢迎回来")
else:
print("请先登录")
4. if-else execution flow
flowchart TD
A["Start"] --> B["Evaluate condition expression"]
B --> C{"Is the condition true?"}
C -->|Yes| D["Execute if code block"]
C -->|No| E["Execute else code block"]
D --> F["Continue with subsequent code"]
E --> F
F --> G["End"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
V. if-elif-else: Multi-branch structure
1. Why elif is needed
In real-world business scenarios, conditional checks often involve more than two cases.
For example, exam scores can be divided into:
- 90 and above: Excellent.
- 80–89: Good.
- 70–79: Average.
- 60–69: Pass.
- Below 60: Fail.
If you use many independent if statements, multiple branches may execute redundantly.
elif can organize multiple mutually exclusive conditions into a single branch chain.
2. Basic syntax
if condition_1:
statement_1
elif condition_2:
statement_2
elif condition_3:
statement_3
else:
default_statement
Execution rules:
- Evaluate the conditions from top to bottom.
- Find the first condition that is true.
- Execute the corresponding code block.
- Skip all subsequent
elifandelsebranches. - If none of the conditions is true, execute
else.
3. Score Grade Example
score = 85
if score >= 90:
print("优秀")
elif score >= 80:
print("良好")
elif score >= 70:
print("中等")
elif score >= 60:
print("及格")
else:
print("不及格")
Output:
良好
The order of evaluation here is very important.
Because conditions are evaluated from top to bottom, once score >= 80 is true, the later conditions will not be evaluated.
4. Multi-branch Execution Flow
flowchart TD
A["Start"] --> B["Check condition 1"]
B --> C{"Condition 1 is true"}
C -->|Yes| D["Execute branch 1"]
C -->|No| E["Check condition 2"]
E --> F{"Condition 2 is true"}
F -->|Yes| G["Execute branch 2"]
F -->|No| H["Check condition 3"]
H --> I{"Condition 3 is true"}
I -->|Yes| J["Execute branch 3"]
I -->|No| K["Execute else branch"]
D --> L["Continue execution"]
G --> L
J --> L
K --> L
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style F fill:#FFF5DE,stroke:#E8D29A,color:#334155
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style I fill:#FFF5DE,stroke:#E8D29A,color:#334155
style J fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style K fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style L fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
5. Execution Features of elif
An if-elif-else branch chain executes at most one branch.
For example:
number = 10
if number > 0:
print("正数")
elif number > 5:
print("大于 5")
else:
print("其他")
Output:
正数
Although number > 5 is also true, the program has already selected the corresponding branch after the first condition became true.
If you want both conditions to be executed separately, you should use two independent if statements:
number = 10
if number > 0:
print("正数")
if number > 5:
print("大于 5")
Output:
正数
大于 5
These two structures have different semantics and cannot be interchanged arbitrarily.
VI. Difference Between Multiple if and if-elif
This is one of the places where beginners are most likely to get confused.
1. Multiple Independent if Statements
Multiple independent if statements are not mutually exclusive.
score = 95
if score >= 60:
print("考试通过")
if score >= 80:
print("成绩良好")
if score >= 90:
print("成绩优秀")
Output:
Exam passed
Good grade
Excellent grade
Each condition is evaluated independently, and every branch whose condition is true is executed.
2. if-elif branch chain
score = 95
if score >= 60:
print("考试通过")
elif score >= 80:
print("成绩良好")
elif score >= 90:
print("成绩优秀")
Output:
Exam passed
Because the first condition is already true, subsequent branches are not executed.
3. Key differences
| Comparison aspect | Multiple independent if statements | if-elif-else |
|---|---|---|
| Condition evaluation | Each condition is evaluated independently | Evaluated in order |
| Number of branches executed | Multiple branches can execute | At most one executes |
| Subsequent conditions | Usually all are evaluated | Skipped after an earlier condition is true |
| Use case | Multiple conditions may be true at the same time | Multiple mutually exclusive options |
| Execution efficiency | May perform more evaluations | Stops after a matching branch is found |
4. How to choose
If the business conditions are independent of one another, use multiple if statements.
If there is a priority or mutual exclusivity relationship among the business conditions, use if-elif-else.
For example:
temperature = 35
if temperature > 30:
print("高温预警")
if temperature > 20:
print("适合穿轻薄衣物")
Both conditions can be true at the same time, so using two independent if statements is more reasonable.
Grade levels, however, are mutually exclusive categories, so if-elif-else is more appropriate.
VII. Conditional Expressions and Truth Value Testing
1. Conditions are not necessarily True or False
Python conditional expressions are not required to return True or False.
As long as an object can be evaluated for truth value, it can be used as an if condition.
name = "Alice"
if name:
print("名称不为空")
Here, name is a string, not a Boolean value.
Python evaluates the condition according to the truth-value rules for strings.
2. Common falsy objects
The following objects are usually false in conditional tests:
| Object | Example |
|---|---|
False |
if False: |
None |
if None: |
| Numeric zero | if 0: |
| Floating-point zero | if 0.0: |
| Empty string | if "": |
| Empty list | if []: |
| Empty tuple | if (): |
| Empty dictionary | if {}: |
| Empty set | if set(): |
Example:
items = []
if items:
print("列表不为空")
else:
print("列表为空")
Output:
The list is empty
3. Common truthy objects
The following objects are usually true:
if 1:
print("执行")
if "Python":
print("执行")
if [1, 2]:
print("执行")
if {"name": "Alice"}:
print("执行")
4. Truth-value testing for custom objects
Custom objects can control their truth value behavior through __bool__() or __len__().
class User:
def __init__(self, active):
self.active = active
def __bool__(self):
return self.active
user = User(True)
if user:
print("用户处于活跃状态")
Things to note:
__bool__()must return an actualboolobject.- If there is no
__bool__(), Python can try to use__len__(). - When
__len__()returns 0, the object is false; when it returns a nonzero value, the object is true. - If neither is defined, ordinary custom objects are usually true by default.
5. Relationship Between Conditional Checks and bool()
You can use bool() to explicitly inspect an object's truth value:
print(bool(0)) # False
print(bool(1)) # True
print(bool("")) # False
print(bool("False")) # True
print(bool([])) # False
print(bool([1])) # True
Note: the string "False" is not the Boolean value False; it is a non-empty string, so the result is True.
VIII. Logical Operations in Conditional Expressions
Conditional statements are often combined with logical operators.
1. and: Logical AND
and requires both conditions to be satisfied.
age = 25
has_ticket = True
if age >= 18 and has_ticket:
print("允许进入")
2. or: Logical OR
or requires at least one condition to be satisfied.
is_admin = False
is_operator = True
if is_admin or is_operator:
print("允许管理部分资源")
3. not: Logical NOT
not is used to invert a truth value.
is_locked = False
if not is_locked:
print("账户可以使用")
4. Combined Conditions
age = 25
is_member = True
has_coupon = False
if age >= 18 and (is_member or has_coupon):
print("满足购买条件")
The logical relationship here is:
- The person must be at least 18 years old.
- At the same time, at least one of the following conditions must be met: being a member or having a coupon.
5. Short-Circuit Evaluation
Python's and and or support short-circuit evaluation (Short-Circuit Evaluation).
For and:
- If the left side is false, the right side is not evaluated.
- If the left side is true, the right side is evaluated.
For or:
- If the left side is true, the right side is not evaluated.
- If the left side is false, the right side is evaluated.
Example:
def check():
print("执行了 check")
return True
if False and check():
print("执行分支")
if True or check():
print("条件成立")
Output:
条件成立
Neither check() call is executed, because the logical expression can already determine the result.
Short-circuit evaluation affects not only performance but also whether function calls and other side effects in an expression occur.
IX. Nested Conditional Statements
1. What Are Nested Conditionals?
A conditional statement can contain other conditional statements inside it; this structure is called nested conditionals (Nested Conditionals).
Example:
age = 25
has_permission = True
if age >= 18:
if has_permission:
print("允许访问")
else:
print("没有访问权限")
else:
print("年龄不符合要求")
Execution order:
- Check the age.
- If the age meets the requirement, then check permissions.
- Execute the corresponding branch based on the permission check result.
- If the age does not meet the requirement, execute the outer
elsedirectly.
2. Multi-Level Nesting Example
age = 25
is_member = True
has_balance = True
if age >= 18:
if is_member:
if has_balance:
print("允许购买")
else:
print("余额不足")
else:
print("请先成为会员")
else:
print("年龄不符合要求")
Although this structure can express complex business logic, too many levels of nesting reduce code readability.
3. Nested Conditional Flow
flowchart TD
A["Start"] --> B{"Age meets requirement?"}
B -->|No| C["Prompt: age does not meet requirement"]
B -->|Yes| D{"Is member?"}
D -->|No| E["Prompt: membership requirement not met"]
D -->|Yes| F{"Is balance sufficient?"}
F -->|No| G["Prompt: insufficient balance"]
F -->|Yes| H["Allow purchase"]
C --> I["End"]
E --> I
G --> I
H --> I
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
style C fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style F fill:#FFF5DE,stroke:#E8D29A,color:#334155
style G fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style I fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
4. Reduce Excessive Nesting
Some conditions can be simplified through logical combination:
age = 25
is_member = True
has_balance = True
if age >= 18 and is_member and has_balance:
print("允许购买")
else:
print("不满足购买条件")
You can also reduce nesting inside functions by returning early:
def can_purchase(age, is_member, has_balance):
if age < 18:
return False
if not is_member:
return False
if not has_balance:
return False
return True
print(can_purchase(25, True, True)) # True
This style is commonly called Guard Clauses and is suitable for handling preconditions and exceptional cases within functions.
10. Comparison Operations in Conditional Statements
1. Common Comparison Operators
| Operator | Meaning | Example |
|---|---|---|
== |
Equal to | a == b |
!= |
Not equal to | a != b |
> |
Greater than | a > b |
< |
Less than | a < b |
>= |
Greater than or equal to | a >= b |
<= |
Less than or equal to | a <= b |
Example:
score = 85
if score >= 60:
print("通过考试")
2. Python Supports Chained Comparisons
Python allows you to write continuous comparisons as in mathematics directly:
age = 25
if 18 <= age < 60:
print("符合年龄范围")
Equivalent to:
if age >= 18 and age < 60:
print("符合年龄范围")
Chained comparisons have the following characteristics:
- They are evaluated from left to right.
- The middle expression is evaluated only once.
- As soon as one comparison fails, evaluation short-circuits and stops.
3. Range Checks
score = 85
if 90 <= score <= 100:
print("优秀")
elif 80 <= score < 90:
print("良好")
elif 60 <= score < 80:
print("及格")
else:
print("不及格")
Here the interval boundaries are stated explicitly, which prevents overlap between the different grades.
4. Avoid Missing Boundaries
For example:
score = 60
if score > 60:
print("通过")
else:
print("不通过")
If the business rule requires that a score of 60 also counts as a pass, it should be written as:
if score >= 60:
print("通过")
else:
print("不通过")
Condition boundaries need to be designed explicitly according to the business rules.
11. Membership and Identity Checks in Conditional Statements
1. Using in to Test Membership
role = "admin"
if role in {"admin", "editor", "operator"}:
print("允许进入管理区域")
2. Using not in to Exclude Specified Values
status = "disabled"
if status not in {"disabled", "blocked"}:
print("账户状态正常")
3. Using is to Test for None
result = None
if result is None:
print("没有查询结果")
4. Don't Confuse == with is
a = [1, 2]
b = [1, 2]
if a == b:
print("两个列表的值相等")
if a is b:
print("两个变量引用同一个对象")
Here the second condition does not hold.
Comparison operations in conditional statements should use the correct operator chosen according to business semantics.
12. Common Patterns for Conditional Statements
1. Testing for Empty Containers
Not recommended:
items = []
if len(items) > 0:
print("有数据")
Recommended:
if items:
print("有数据")
When testing for an empty list, empty dict, or empty set, you can use the object's truth value directly.
2. Testing for None
Recommended:
if value is None:
print("没有数据")
Not recommended:
if value == None:
print("没有数据")
3. Don't Repeat the Same Condition
Not recommended:
if age >= 18:
print("成年")
if age >= 18:
print("可以申请")
If both actions need to be executed under the same condition, you can merge them:
if age >= 18:
print("成年")
print("可以申请")
But if the two checks belong to independent business logic, keeping them as separate checks may also be clearer.
4. Avoid Meaningless Boolean Comparisons
Not recommended:
if is_active == True:
print("账户正常")
Recommended:
if is_active:
print("账户正常")