Python 3 - 条件判断
Python 3 - 决策
Section titled “Python 3 - 决策”决策是编程的基础。它允许您的程序根据特定条件是真还是假来执行不同的代码块。这使得程序能够动态地对不同的输入或情况做出反应。
决策结构评估表达式,这些表达式的结果是一个布尔值:True(真)或 False(假)。根据这个结果,程序选择要遵循的路径。
想象一个流程图,您会遇到一个问题(条件)。如果答案是“是”(True),您就沿着一条路径走;如果答案是“否”(False),您就沿着另一条路径走。Python 提供了特定的语句来实现这种逻辑。
真值测试 (Truth Value Testing)
Section titled “真值测试 (Truth Value Testing)”在 Python 中,条件在一个布尔上下文中进行评估。虽然明确的布尔值是 True 和 False,但其他值在条件语句中也可以被视为真或假:
- 被视为 False 的值:
None,False(布尔值),任何数字类型的零(0,0.0,0j),空序列('',(),[]),空映射({}),空集合(set()),以及__bool__()返回False或__len__()返回0的对象。 - 被视为 True 的值:所有其他值,包括非空序列/集合和非零数字。
Python 提供以下语句用于决策:
| 语句 | 描述 |
|---|---|
if 语句 | 仅当指定的条件为 True 时才执行一个代码块。 |
if...else 语句 | 如果条件为 True,则执行一个代码块;如果条件为 False,则执行另一个代码块。 |
if...elif...else 语句 | 按顺序检查多个条件。执行对应于第一个 True 条件的代码块。如果之前没有任何条件为 True,则执行可选的 else 块。 |
嵌套 if 语句 | 允许您在其他 if、elif 或 else 语句的代码块内放置 if、elif 或 else 语句,创建更复杂的决策树。 |
最简单的形式。只有当条件评估为 True 时,紧跟在 if 语句后面的代码块才会被执行。
if condition: # Code to execute if condition is True statement(s)#!/usr/bin/env python3
temperature = 35
if temperature > 30: print("It's a hot day!")
print("Goodbye!") # This line executes regardless of the condition输出:
It's a hot day!Goodbye!if...else 语句
Section titled “if...else 语句”当 if 条件为 False 时,提供另一条路径。
if condition: # Code to execute if condition is True statement(s)_if_trueelse: # Code to execute if condition is False statement(s)_if_false#!/usr/bin/env python3
age = 17
if age >= 18: print("You are eligible to vote.")else: print("You are not eligible to vote yet.")
print("Processing complete.")输出:
You are not eligible to vote yet.Processing complete.if...elif...else 语句
Section titled “if...elif...else 语句”elif 代表 ‘else if’。它允许您按顺序检查多个条件。第一个评估为 True 的条件将执行其代码块,其余的 elif/else 块将被跳过。最后的 else 块是可选的,如果之前的任何 if 或 elif 条件都不是 True,则执行它。
if condition1: # Code for condition1 True statement(s)_1elif condition2: # Code for condition1 False, condition2 True statement(s)_2elif condition3: # Code for condition1/2 False, condition3 True statement(s)_3# ... more elif blocks as neededelse: # Code if none of the above conditions are True statement(s)_else示例:评分系统
Section titled “示例:评分系统”#!/usr/bin/env python3
score = 75
if score >= 90: grade = 'A'elif score >= 80: grade = 'B'elif score >= 70: grade = 'C'elif score >= 60: grade = 'D'else: grade = 'F'
print(f"Your score is {score}, which corresponds to grade: {grade}")输出:
Your score is 75, which corresponds to grade: C嵌套 if 语句
Section titled “嵌套 if 语句”您可以将条件语句放在其他条件语句内部,以处理更复杂的逻辑。
#!/usr/bin/env python3
num = 15
if num >= 0: print("Number is non-negative") if num == 0: print("Number is Zero") else: print("Number is Positive") if num % 2 == 0: print("Number is Even") else: print("Number is Odd")else: print("Number is Negative")输出:
Number is non-negativeNumber is PositiveNumber is Odd虽然可以进行嵌套,但过度的嵌套会使代码难以阅读。考虑将复杂的嵌套条件重构为单独的函数或尽可能使用其他控制流结构。
单行语句块(内联 if)
Section titled “单行语句块(内联 if)”如果 if(或 elif、else)的代码块只包含一个语句,您可以将其放在与头部同一行。然而,PEP 8 等风格指南通常不鼓励这样做,尤其对于复杂的操作,以提高可读性。
#!/usr/bin/env python3
var = 100if var == 100: print(f"Value of expression is {var}") # Single statement on same line
print("Good bye!")输出:
Value of expression is 100Good bye!一种更常见且通常更受欢迎的单行条件结构是“三元运算符”或条件表达式:
#!/usr/bin/env python3
age = 20status = "Adult" if age >= 18 else "Minor"print(f"The person is a {status}.")输出:
The person is a Adult.