# Python实现case/switch

Python没有直接支持case/switch结构，通常是通过 `if / elif / else` 来实现类似结构。

以下是一个采用字典来实现case/switch结构，值得借鉴：

```python
# define the function blocks
def zero():
    print "You typed zero.\n"

def sqr():
    print "n is a perfect square\n"

def even():
    print "n is an even number\n"

def prime():
    print "n is a prime number\n"

# map the inputs to the function blocks
options = {0 : zero,
           1 : sqr,
           4 : sqr,
           9 : sqr,
           2 : even,
           3 : prime,
           5 : prime,
           7 : prime,
}
```

然后采用如下调用来实现：

```python
options[num]()
```

另外一种巧妙的字典方法：

```python
def f(x):
    return {
        'a': 1,
        'b': 2,
    }[x]
```

使用字典[get(key\[, default\])](https://docs.python.org/2/library/stdtypes.html#dict.get)方法

```python
def f(x):
    return {
        'a': 1,
        'b': 2
    }.get(x, 9)    # 9 is default if x not found
```

## 参考

* [What is the Python equivalent for a case/switch statement? \[duplicate\]](https://github.com/huataihuang/cloud-atlas-draft/tree/6f3204fffc11cf006abd394631e2598d98b415c3/develop/python/startup/What%20is%20the%20Python%20equivalent%20for%20a%20case/switch%20statement?%20\[duplicate]/README.md)
* [Replacements for switch statement in Python?](https://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://huataihuang.gitbook.io/cloud-atlas-draft/develop/python/startup/python_case_switch_statement.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
