---
title: 2020 KGHS i2trc2 Python
---
# Python Basic Syntax - Variables
###### tags:`2020KGHS` `i2trc2`
[Toc]
# Varaiables
## Numbers
>In addition to `int` and `float`, Python supports other types of numbers, such as `Decimal` and `Fraction`. Python also has built-in support for `complex` numbers, and uses the j or J suffix to indicate the imaginary part (e.g. 3+5j).
### 運算
1. 數學運算:加法 `+`、減法 `-`、乘法 `*` 、取餘 `%` 、整數除法 `//` 、指數 `**`
2. 關係運算子:大於 `>`,小於 `<`,等於 `==`,不等於 `!=`,小於等於 `<=`,大於等於 `>=`
3. 位元運算:`&` (AND), `|` (OR),`~` (NOT),`^` (XOR)
4. 邏輯運算:`and`、`or`、`not`
## String
用 `'`或`"` 包住即可變成字串
```python=
>>> string1 = '"abc" efg'
得到 "abc"efg
>>> string2 = "'abc'efg"
得到 'abc'efg
# 但你不能這樣寫!
string3 = "'abc"efg'
```
用 `\` 可以輸入跳脫字元
```python
>>> print('C:\some\name') # here \n means newline!
C:\some
ame
>>> print(r'C:\some\name') # note the r before the quote
C:\some\name
```
### String concatenate
```python=
>>> prefix = 'Py'
>>> prefix + 'thon'
'Python'
```
### String Indexing
index 可以是負數,但不能超過字串或是 list 的長度!
```python=
>>> word = 'Python'
>>> word[0] # character in position 0
'P'
>>> word[5] # character in position 5
'n'
>>> word[-1] # last character
'n'
>>> word[-2] # second-last character
'o'
```
用 `:` 表示 前半段 或 後半段,注意左邊的數字包含,右邊的數字不包含,也就是 $[x, y)$
```python=
>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'
```
:::warning
單獨修改 string 中一個字或字串是不允許的,應該使用特殊的函數,例如
- [replace](https://www.w3schools.com/python/ref_string_replace.asp): `string.replace(oldvalue, newvalue, count)`
:::
### String format
如果要在字串中穿插變數值,甚至指定顯示位數或資料形態要怎麼做呢?
在 C 中,我們可以用格式化的表示法,在 Python 中我們也有類似的語法。
```python=
age = 36
print("My name is John, and I am {}".format(age))
# 顯示小數點後兩位
# 也可以指定要放的順序
print("2={2}, 1={1}, 0={0}".format(0, 1, 2))
```
python 已經內建許多對字串的操作,需要的時候再去找就可以了。
[Reference](https://www.w3schools.com/python/python_strings.asp)
## Lists
### Indexing
```python
>>> cubes = [1, 2, 27]
# 修改
>>> cubes[1] = 4
[1, 4, 27]
>>> cubes = [1, 8, 27]
>>> cubes[:]
[1, 8, 27]
```
Python 沒有內建如 C/C++ 固定大小的 array (需使用 numpy library),取而代之的是稱為 `list` ,類似 linked list 可以自由增減長度,上面對 string 的操作幾乎都可以對 list 操作。
:::info
slicing 時,左邊的數字包含,右邊的數字不包含,這個特性在許多場景非常好用,例如 for 迴圈
```python=
list1 = [0, 1, 2, 3, 4]
for i in range(len(list1)):
print(list1[i])
# i from 0 to 4
# But len(list1) = 5
```
P.S. 這邊只是為了示範 indexing 的用法,事實上以上程式碼可寫成
```python=
list1 = [0, 1, 2, 3, 4]
for l in list1:
print(l)
```
:::
### append
```python
>>> cubes = [1, 8, 27]
>>> cubes.append(4 ** 3)
[1, 8, 27, 64]
```
### del (delete)
```python
>>> cubes = [1, 8, 27]
>>> del(cubes[1])
[1, 27]
```
:::warning
#### tuple
tuple 跟 list 很類似,最大差別在 tuple 的內容不可以變更
tuple: (1, 2, 3)
list: [1, 2, 3]
:::
### Len
取得 List 長度
```python
length = len(list1)
```
### Nested List
Python list 可以不同型態、不同長度放在一起
```python=
>>> a = ['a', 'b', 'c']
>>> n = [1, 2]
>>> m = [a, n]
[['a', 'b', 'c'], [1, 2]]
>>> m[0][1]
'b'
```
## Dictionaries
在 Python 、 Javascript 中提供一種很特殊的型態稱為 **dictionary** ,以 `key` 跟 `value` 組成,使用上類似於以 **字串** 作為索引
```python=
dict1 = {}
dict1['name'] = 'vincent'
dict1['id'] = '123456789'
dict1['birth'] = '0123'
```
### nested dictionary
```python=
people = {1: {'name': 'John', 'id': '741515152', 'birth': '1220'},
2: {'name': 'Marie', 'id': '464897121', 'birth': '0509'}}
# 新增一個型態為 dict 、key 為 3 的元素
people[3] = {}
people[3]['name'] = 'Luna'
people[3]['id'] = '794515254'
people[3]['bitrh'] = '0519'
people[3]['married'] = 'No'
# 刪除 key 3 中 key 為 married 的元素
del people[3]['married']
```
### 取得 key 值
```python=
>>> dict1.keys()
dict_keys(['name', 'id', 'birth'])
```
### 取得 dict 中 key 與 value 的資料
```python=
>>> dict1.items()
dict_items([('name', 'vincent'), ('id', '123456789'), ('birth', '0123')])
```
:::info
JSON 是一個被廣泛應用的資料交換格式,支援許多不同語言,現今許多應用程式資料也以 JSON 格式儲存或傳輸,例如網頁 request 、 設定檔、甚至小型資料庫等等。副檔名為 `.json`
Python 中 dictionary 的使用與 JSON 相當相似,因此轉換也非常方便。
[[wiki]](https://zh.wikipedia.org/wiki/JSON) [[json library]](https://docs.python.org/3/library/json.html)
:::
## Reference
1. [Python Nested Dictionary](https://www.programiz.com/python-programming/nested-dictionary)
2. [An Informal Introduction to Python](https://docs.python.org/3/tutorial/introduction.html)