Python 条件语句完全指南:if、else、elif 与字典模拟 switch-case
Python 条件语句是什么?
条件语句让程序基于布尔表达式执行不同代码块。Python 中 if 语句是驱动决策的核心构造。
本指南探索 if、else、elif 及字典模拟 switch-case,每节含简洁示例。
- 理解
if语句 if条件为假时的行为- 使用
else分支 else常见陷阱- 用
elif处理多分支 - 三元表达式简化逻辑
- 嵌套
if语句 - 字典实现 switch-case 模式
Python if 语句基础
语法
if expression:
# 表达式为 True 执行
else:
# 表达式为 False 执行
示例:
def main():
x, y = 2, 8
if x < y:
st = "x is less than y"
else:
st = "x is not less than y"
print(st)
if __name__ == "__main__":
main()
if 条件为假时会发生什么?
条件为 False 且无 else 时,if 体被跳过,程序继续执行后续代码。
条件失败示例:
def main():
x, y = 8, 4
if x < y:
st = "x is less than y"
else:
st = "x is greater than or equal to y"
print(st)
if __name__ == "__main__":
main()
使用 else 分支
else 块在前置 if 为 False 时执行,适合二元决策。
def main():
x, y = 8, 4
if x < y:
st = "x is less than y"
else:
st = "x is greater than y"
print(st)
if __name__ == "__main__":
main()
else 常见错误
两值相等时,else 可能错误报告“greater”或“less”。
def main():
x, y = 8, 8
if x < y:
st = "x is less than y"
else:
st = "x is greater than y" # x==y 时错误
print(st)
if __name__ == "__main__":
main()
引入 elif 处理多分支
elif 允许在初始 if 后测试额外条件,避免上述落穿错误。
def main():
x, y = 8, 8
if x < y:
st = "x is less than y"
elif x == y:
st = "x is the same as y"
else:
st = "x is greater than y"
print(st)
if __name__ == "__main__":
main()
三元表达式简化逻辑
Python 单行语法让简单比较更简洁:
def main():
x, y = 10, 8
st = "x is less than y" if x < y else "x is greater than or equal to y"
print(st)
if __name__ == "__main__":
main()
嵌套 if 语句
多变量依赖决策时用嵌套条件。
total = 100
country = "AU" # 改为 "US" 测试另一分支
if country == "US":
if total <= 50:
print("Shipping Cost is $50")
elif total <= 100:
print("Shipping Cost is $25")
elif total <= 150:
print("Shipping Costs $5")
else:
print("FREE")
elif country == "AU":
if total <= 50:
print("Shipping Cost is $100")
else:
print("FREE")
Python 中的 Switch-Case 替代方案
Python 无原生 switch,但字典查找提供同等清晰度与效率。
def switch_example(argument):
switcher = {
0: "This is Case Zero",
1: "This is Case One",
2: "This is Case Two",
}
return switcher.get(argument, "nothing")
if __name__ == "__main__":
argument = 1
print(switch_example(argument))
总结
- if – 条件为真时执行。
- else – 前置
if为假时执行。 - elif – 顺序添加额外布尔检查。
- 三元表达式简化简单比较。
- 嵌套
if处理多维决策。 - 字典查找提供清晰 switch-case 替代。
Python
- 掌握 C# 条件逻辑:if、if-else、if-else if 与嵌套 if 语句完全指南
- 掌握 C# switch 语句:语法、示例与最佳实践
- 掌握 C++ switch-case 语句:语法、流程与计算器实战案例
- C 语言条件语句精通:if、else、嵌套与多重分支
- C 语言 switch 语句完全指南:语法、流程与计算器实例
- 掌握 C++ switch-case:语法、用法与实战示例
- Python语句、缩进与注释:清晰指南
- 精通Python If…Else 语句
- 精通Python Pass语句:实战指南
- Python print() 函数完全指南:基础用法、空行打印与自定义结束符
- 精通 Java if…else:控制流全解析
- 精通 Java Switch 语句:语法、用法与最佳实践