---
# System prepended metadata

title: Python 基礎語法-Part 1
tags: [python]

---

# Python 基礎語法-Part 1
###### tags: `python`
:::danger
:exclamation::exclamation::exclamation: <font color=red>**Python 非常注重 Tab 、 空白 、 換行**</font>
:::
## Zen of Python
:::warning
**希望你寫Python時應該抱有的精神**
:::
在Python 中輸入`import this`
```
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
```

## 一.數據類型
### 變數
|    型態    |                          Code                          |
|:----------:|:------------------------------------------------------:|
|  Integer   |                       `iv = 10`                        |
|   Float    |                      `fv = 12.3`                       |
|  Complex   |                     `cv = 3 + 5j`                      |
|   String   |                 `sv = 'hello python'`                  |
|    Bool    |                      `bv = True`                       |
|    None    |                      `nv = None`                       |
|    list    |         `list = ['abcd',786,2.23,'john',70.2]`         |
|   Tuples   |        `tuple = ('abcd',786,2.23,'john',70.2)`         |
| Dictionary | `dict = {'name': 'john','code':6734, 'dept': 'sales'}` |
* 多重分配
:::success
a = b = c = 1
a, b, c = 1, 2, "john"
:::
### 字串
|        符號        | Code                                               |
|:------------------:|:-------------------------------------------------- |
|    單引號（'）     | `word = 'word' `                                   |
|    雙引號（"）     | `sentence = "This is a sentence."`                 |
| 三引號（'''或"""） | `paragraph = """This is a paragraph.`              |
|     **可跨行**     | `It is made up of multiple lines and sentences.""` |
* 索引
```
str = 'Hello World!'

print (str)          # Hello World!
print (str[0])       # H
print (str[2:5])     # llo
print (str[2:])      # llo World!
print (str * 2)      # Hello World!Hello World!
print (str + "TEST") # Hello World!TEST
```
### 序列(Range)
* 創建：`Range(stop)`、`Range(start, stop)`、`Range(start, stop, step)`

:::danger
**Range** 、 **Tuples**  一旦被創造，將無法修改內容
:::
#### 操作方法
|                          操作                          |         Code         |
|:------------------------------------------------------:|:--------------------:|
|                     取得容器的長度                     |       `len(s)`       |
|                   取得容器內的最小值                   |       `min(s)`       |
|                   取得容器內的最大值                   |       `max(s)`       |
|                  X元素在S容器的索引值                  | `s.index(x[,i[,j]])` |
|             X這個元素在S這個容器內出現幾次             |     `s.count(x)`     |
|              index為i的元素的內容置換為X               |      `s[i] = x`      |
|              index從i到j的元素內容置換為X              |     `s[i:j] = t`     |
|   index從i到j的元素，以step為k的方式，將內容置換為X    |    `s[i:j:k] = t`    |
|                把index從i到j的元素刪除                 |     `del s[i:j]`     |
|       index從i到j的元素，以step為k的方式刪除元素       |    `del s[i:j:k]`    |
|                  將X塞到S容器的最後面                  |    `s.append(x)`     |
|                 將S容器的內容全部刪除                  |     `s.clear()`      |
|                       複製S容器                        |      `s.copy()`      |
|                      同 s = s + t                      |    `s.extend(t)`     |
| 在S容器index為i的位置將X插入，原有的元素(們)將會往後移 |   `s.insert(i,x)`    |
|          將index為i的元素取出，並將其移出容器          |     `s.pop([i])`     |
|                   刪除第一個找到的X                    |    `s.remove(x)`     |
|                  讓容器的內容順序顛倒                  |    `s.reverse()`     |
### 數據類型轉換
|                     操作                      |          Code           |
|:---------------------------------------------:|:-----------------------:|
| 將x轉換為int。如果x是字符串，則基數指定基數。 |    `int(x [,base])`     |
|                將x轉換為float                 |       `float(x)`        |
|                創建一個complex                | `complex(real [,imag])` |
|          將對象x轉換為字符串表示形式          |        `str(x)`         |
|           將對象x轉換為表達式字符串           |        `repr(x)`        |
|           計算字符串並返回一個對象            |       `eval(str)`       |
|                將s轉換為tuple                 |       `tuple(s)`        |
|                 將s轉換為list                 |        `list(s)`        |
|                 將s轉換為set                  |        `set(s)`         |
|                 將s轉換為dict                 |        `dict(d)`        |
|              將s轉換為frozenset               |     `frozenset(s)`      |
|               將整數轉換為字符                |        `chr(x)`         |
|            將整數轉換為Unicode字符            |       `unichr(x)`       |
|           將單個字符轉換為其整數值            |        `ord(x)`         |
|          將整數轉換為十六進位字符串           |        `hex(x)`         |
|           將整數轉換為八進位字符串            |        `hex(x)`         |

---

## 二.運算符
### 數學運算符
| 運算子 |        功能        |
|:------:|:------------------:|
| x + y  |        X加Y        |
| x - y  |        X減Y        |
| x * y  |        X乘Y        |
| x / y  |       X除以Y       |
| x // y | X除以Y，只取整數解 |
| x % y  |   求X除以Y的餘數   |
| x ** y |      X的Y次方      |
### 比較運算符
| 運算子 |      功能      |
|:------:|:--------------:|
| x < y  |   X是否小於Y   |
| x <= y | X是否小於等於Y |
| x > y  |   X是否大於Y   |
| x >= y | X是否大於等於Y |
| x == y |   X是否等於Y   |
| x != y |  X是否不等於Y  |
### 賦值運算符
|  運算子   |    功能    |     | 運算子  |    功能    |
|:---------:|:----------:| --- |:-------:|:----------:|
| c = a + b | c = a + b  |     | c /= a  | c = c / a  |
|  c += a   | c = c + a  |     | c %= a  | c = c % a  |
|  c -= a   | c = c - a  |     | c -= a  | c = c - a  |
|  c \*= a  | c = c \* a |     | c //= a | c = c // a |
### 布林運算符
|     運算子      |                   功能                   |
|:---------------:|:----------------------------------------:|
| a or b (a\|\|b) |      A或B其中一個條件成立就回傳True      |
| a and b (a&&b)  |       A或B兩個條件都成立才回傳True       |
|      not A      | 如果A為True，則回傳False，反之則回傳True |
### 按位運算符
a = 0011 1100
b = 0000 1101
| 運算子 |           功能           |
|:------:|:------------------------:|
|  a＆b  |       & Binary AND       |
| a \| b |       \| Binary OR       |
| a ^ b  |       ^ Binary XOR       |
|  〜a   | ~ Binary Ones Complement |
| a << 2 |   << Binary Left Shift   |
| a >> 2 |  >> Binary Right Shift   |
### Membership 運算符
|   運算子   |              功能              |
|:----------:|:------------------------------:|
|   x in y   |  檢查X是否存在於y這個容器之中  |
| x not in y | 檢查X是否不存在於y這個容器之中 |
### 運算符優先級
1. **
2. ~ + -  (+@ and -@)
3. \* / % //
4. \+ \-
5. \>> <<
6. &
7. ^ |
8. <= < > >= (比較運算子)
9. < > == !=
10. = %= /= //= -= += *= \*\*=
11. is isnot
12. in notin
13. not or and

---
## Reserved Words
![](https://i.imgur.com/xESlcdj.png)

:::warning
[Python 基礎語法-Part 2](/6EVIPrRXRrKJY7LIrBDkmA)
:::


