亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> Python

Python 条件语句完全指南:if、else、elif 与字典模拟 switch-case

Python 条件语句是什么?

条件语句让程序基于布尔表达式执行不同代码块。Python 中 if 语句是驱动决策的核心构造。

本指南探索 if、else、elif 及字典模拟 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))

总结

Python

  1. 掌握 C# 条件逻辑:if、if-else、if-else if 与嵌套 if 语句完全指南
  2. 掌握 C# switch 语句:语法、示例与最佳实践
  3. 掌握 C++ switch-case 语句:语法、流程与计算器实战案例
  4. C 语言条件语句精通:if、else、嵌套与多重分支
  5. C 语言 switch 语句完全指南:语法、流程与计算器实例
  6. 掌握 C++ switch-case:语法、用法与实战示例
  7. Python语句、缩进与注释:清晰指南
  8. 精通Python If…Else 语句
  9. 精通Python Pass语句:实战指南
  10. Python print() 函数完全指南:基础用法、空行打印与自定义结束符
  11. 精通 Java if…else:控制流全解析
  12. 精通 Java Switch 语句:语法、用法与最佳实践