问题:Python 没有像其他编程语言 (如 C++ 或 Java) 那样的内置 switch-case 语句。请解释如何使用 if-elif-else 语句、字典和第三方库等替代方法在 Python 中实现类似的行为。

解决方案:

使用 if-elif-else 语句: 您可以使用一系列 if、elif 和 else 语句在 Python 中实现类似开关情况的行为。每个 if 或 elif 块都会检查一个条件,如果条件为真,则执行块内的代码。

def switch_case_example (case):
  if case == "option1":
    print("Option 1 selected")
  elif case == "option2":
    print ("Option 2 selected")
  elif case == "option3":
    print("Option 3 selected")
  else:
    print("Invalid option")

# Usage :
switch_case_example ("option2") # "Option 2 selected"

Python switch-case 语句