> For the complete documentation index, see [llms.txt](https://lamsaodecode.gitbook.io/python-reference/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lamsaodecode.gitbook.io/python-reference/cau-truc-dieu-khien.md).

# Control Flow

## &#x20;**Conditional statements if**

Câu lệnh if được sử dụng để kiểm tra một điều kiện: nếu điều kiện là đúng sẽ chạy một khối các câu lệnh (được gọi là if-block)**.**

```python
if condition:
    statements
```

Khối else sẽ được thực thi nếu điều kiện trong if là sai

```python
if 1 > 2:
    print("Number 1 is greater than number 2")
else:
    print("The number 1 cannot be greater than the number 2")
```

Khi ta phải kiểm tra thêm một điều kiện nữa nếu trong if là sai ta có thể sử dụng elif

```python
numberInput = int(input('Enter a number: '))
if numberInput == 1:
    print("You just entered the number 1")
elif numberInput == 2:
    print("You just entered the number 2")
else:
    print("The number you entered is not 1 and 2")
```

Chúng ta có thể đặt các khối lệnh if lồng nhau:

```python
if numberInput == 1:
    print("Number 1")
else:
    if numberInput == 2:
        print("Number 2")
    else:
        print("The number you entered is not 1 and 2")
```

## Switch

Có một điều đặc biệt hơn các ngôn ngữ khác là Python không có Switch case. Thay vào đó chúng ta có thể sử dụng if...elif....else để thay thế cấu trúc switch case (hơi bất tiện nhỉ, thế nếu mà có 8 - 10 case thì cứ if else thế này chắc khó đọc quá?)

Ngoài cách dùng if else trên có thể sử dụng cách sau:

```python
switcher = {
    'A': 1,
    'B': 2,
    'C': 3,
    'D': 4,
    'E': 5,
    'F': 6
}
switcher.get(key, "nothing")
```

Đoạn code trên key tương tự đầu vào của hàm switch nếu key thỏa mãn 1 giá trị nào đó thì sẽ trả về giá trị đúng. nếu key ko tồn tại thì sẽ trả về mặc định nothing.

```python
switcher.get('A', "nothing") => 1
switcher.get('G', "nothing") => nothing
```

Ví dụ khác:

```python
def one():
    return 'January'
def two():
    return 'February'
def three():
    return 'March'
def four():
    return 'April'

switcher = {
    1: one,
    2: two,
    3: three,
    4: four,
}
func = switcher.get(key, lambda: ‘nothing’)
print func()
```

## Follower me

* **Facebook**: [https://www.facebook.com/lamsaodecode](https://www.facebook.com/100013678592616)
* **Blog:** <https://lamsaodecode.blogspot.com>
* **Github:** <https://lamsaodecode.github.io/introduction>
