---
# System prepended metadata

title: Python by white
tags: [2025 NISRA Enlightened]

---

:::info
# Python
講師：white
時間：8/27 10:00~12:00
課程簡報: https://docs.google.com/presentation/d/1P88y2jwDgaW_vLbzHduc-ioi653yo2N-eoO3ACZrbDQ/edit?usp=sharing
課程程式碼範例檔案: https://drive.google.com/drive/folders/1A1qOoZ-nBJf9EQVSEMmvQ4XrlSpgbXF9?usp=sharing
:::

## 大綱(Outline)
1. [Python 安裝](#Python-安裝) 
2. [資料型態與基本語法](#基本語法)
3. [控制結構](#控制結構Control-Structures)
4. [迴圈](#迴圈Loops)
5. [函式](#函數Functions) 
6. [類別](#類別Class)
7. [模組](#模組)
8. [凱薩密碼實作](#凱薩密碼Caesar-Cipher) 


## Python 安裝
- 到 Python 官網下載 `.exe` 
- 官網：<https://www.python.org/downloads/>
![python install](https://hackmd.io/_uploads/HkAhRHotll.png)

- Visual Studio Code
![vscode extension install](https://hackmd.io/_uploads/r1XJyLsKlx.png)


## 基本語法
### 資料型態(Data Types)
- **資料**：程式中數據的基本單位
- **資料型態**：資料的分類

| 類型      | 說明  | 範例               |
| ------- | --- | ---------------- |
| `int`   | 整數  | 1、2、3、…          |
| `float` | 浮點數 | 1.1、1.01、1.001、… |
| `bool`  | 布林值 | `True`、`False`   |
| `str`   | 字串  | `"ABC"` 、 `'NISRA'` |

註: python 使用 單引號或雙引號都可以表示成字串

- **list（陣列）**：一種有順序、可變動的資料集合
```python=
data = [1, 2, 1.1, 'Hello', True]
data.append(3)

print(data)
print(data[0])        #1
print(data[-1])       #3
print(data[0:2])      #[1, 2]
print(data[1:])       #[2, 1.1, "Hello", True, 3]
print(data[:])        #[1, 2, 1.1, "Hello", True, 3]
```
- **dictionary（字典）**：`key-value` 資料組合
```python=
data = {
    'a': 123,
    'b': 3.14159,
    'c': False,
    'd': 'Hello',
    'e': [456, 7.89, True, 'World']
    
}
print(data)             
print(data["a"])        # 123
print(data["e"][1])     # 7.89
```


## IO
#### User Input
```python=
user_input = input('Enter anything: ')
## Default input is string
print(user_input)
print(type(user_input))

int_input = int(input('Enter a number: '))
## Convert input to integer
print(int_input)
print(int_input + 1)
print(type(int_input))

split_input = input('Enter two number: ').split()
## Split input by space
print(split_input)
print(type(split_input))
```

#### Print
```python=
name = 'Example'
number = 123

print(name, number)
print('{} {}'.format(name, number))
print(f'Name: {name}, Number: {number}) # Example 123

```

## Operators
| 類別                   | 運算子                                 |
| -------------------- | ----------------------------------- |
| Arithmetic Operators | `+`, `-`, `/`, `*`, `%`, `//`, `**` |
| Assignment Operators | `=`, `+=`, `-=`, `*=`, `/=`         |
| Comparison Operators | `==`, `!=`, `<`, `>`, `<=`, `>=`    |

:::warning
`縮排` 和 `:` 在 python 中是很重要的!!!
:::
## 控制結構(Control Structures)
### 基本語法 `if`
語法結構:
```python
if (布林值):
    # 若布林值為 True 執行
```
語法示範:
```python=
a = 123
if a == 123:
    print('a is 123')
```

```python=
a = 456
if a == 123:
    print('a is 123')
print('end')
```


### 基本語法 `if-else`
語法結構:
```python
if (布林值):
    # 若布林值為 True 執行
else:
    # 若布林值為 False 執行
```
語法示範:
```python=
a = 5
if a > 5:
    print('a is more than 5')
else:
    print('a is less than 5')
```


### 基本語法 `if-elif-else`
語法結構:
```python
if (布林值):
    # 若布林值為 True 執行
elif (布林值):
    # 若布林值為 True 執行
else:
    # 若兩個布林值都是 False，執行
```
語法示範:
```python=
a = 5
if a > 5:
    print('a is more than 5')
elif a == 5:
    print('a is 5')
else:
    print('a is less than 5')
```


### Lab01
Simple Calculator
#### Sample Input:
```
3 + 2
3 - 2
3 * 2
3 / 2
```
#### Sample Output:
```
5
1
6
1
```

## 迴圈(Loops)

### `for` 迴圈
語法結構:
```python
for 變數名稱 in (串列 or 字串):
    # 程式碼
```
將串列中的項目 / 字串中的字元逐一取出

語法範例:
```python=
data = [1, 2, 3, 4, 5]

for i in data:
    print(i, end=' ')
```


### `for` ＆ `range()` 函數
語法結構:
```python
for 變數名稱 in range(a, b, c): 
    # 程式碼
```
`a` = 起始點、`b` = 結束點、`c` = 增加值
- `a` 可省略，預設為 `0`
- `c` 可省略，預設為 `1`

語法範例:
```python=
a = []
for i in range(1, 5):
    a.append(i)
print(a)
# [1, 2, 3, 4]

b = []
for i in range(1, 5, 2):
    b.append(i)
print(b)
# [1, 3]

c = []
for i in range(5):
    c.append(i)
print(c)
# [0, 1, 2, 3, 4]

```


### `while` 迴圈
語法結構:
```python
while (布林值):
    # 布林值為 True 時執行
```
語法範例:
```python=
a = 0
while a < 5:
    print(a, end=' ')
    a += 1
```

```python=
a = 0
while True:
    print(a, end=' ')
    a += 1
    if a > 5:
        break
    
```


### Lab02
Square Printer
**Sample Input:**
```
2
3 2
4 3
```

**Sample Output:**
```
###
###

####
####
####
```

## 函數(Functions)

- 函式：包裝在一個區塊內的程式碼，方便重複呼叫使用  
- 先**定義**（建立）函式，才能**呼叫**（使用）函式

### 定義函式
```python=
def 函式名稱(參數名稱):
    # 程式碼
    return ()  # 程式結束點、return 內可以寫資料、參數或是變數
```

### 呼叫函式
```python
函式名稱(參數資料)
```

### 範例
```python=
def area(width, height):
    ans = width * height
    return ans
print(area(10, 20))
```

## 類別(Class)
- 一種 "藍圖" 
- 帶有獨立不同的屬性 / 設定
- 可以依照不同的藍圖建構出不同的物體
```python=
class Car():
    def __init__(self): ## 建立預設屬性
        self.brand = 'Toyota'
        self.wheel = 4
        self.color = 'Red'
        self.price = 1000000

myCar = Car()
print(myCar.brand)
print(myCar.wheel)
print(myCar.color)
print(myCar.price)
    
```
### 建立類別
```python=
class Car():
    pass
```

### `__init__`
- 建立預設屬性 / 預設資料
- 帶有 `self` 參數代表建立的物件
- 可省略不定義
```python=
class Car():
    def __init__(self): ## 建立預設屬性
        self.brand = 'Toyota'
        self.wheel = 4
        self.color = 'Red'
        self.price = 1000000
```
### 類別中建立功能
- 在 class 中增加函數
- 執行和該類別有關的功能
- 增加類別物件安全性
```python=
class Car():
    def __init__(self): ## 建立預設屬性
        self.brand = 'Toyota'
        self.wheel = 4
        self.color = 'Red'
        self.price = 1000000
    def get_Price(self):
        print(self, price)
        
    def set_Price(self, price):
        self.price = price
    
    def sell(self, customer):
        print(self.brand + "的車子賣給了" + customer)
        
myCar = Car()
myCar.get_Price()

myCar.set_Price(2000000)
myCar.get_Price()

myCar.sell('John')
        
```


## 模組
- 存在於其他任意檔案的程式碼 / 類別
- 分類
    - 內建模組
    - 標準庫模組
    - 第三方模組
    - 自訂模組 (自製模組)

### 引用模組
- import ...
- from ...import ...

範例:
```python=
import datetime
from datetime import date

print(datetime.datetime.now())
print(data.today())

```

```python=
import math

print(math.pi)
print(math.fabs(-3.14))
print(math.sqrt(64))

```

### 自訂 / 自製模組
- 將共用的程式打包成模組，透過其他程式的引用
- 自訂函式的檔案要和使用的程式檔放在一起

```python=
# Test.py
def talk(msg):
    print(msg)

def add(a, b):
    return a + b

def sub(a, b):
    return a - b
```

```python=
import Test

Test.talk('Hello')
print(Test.add(1, 2))
print(Test.sub(1, 2))
```


## 凱薩密碼(Caesar Cipher)

- 替換式加密
- 架構:
```mermaid
flowchart LR;
A[明文] --字母表偏移--> B[密文]
```

![ASCII Table](https://hackmd.io/_uploads/Hkf_DkhKge.png)


### 範例

- 密文to明文
```mermaid
flowchart LR;
A[密文：<br><code>attackatonce</code>] --偏移量=5--> B[明文：<br><code>exxegoexsrgi</code>]
```
- 明文to密文
```mermaid
flowchart LR;
A[明文：<br><code>udymtsnxymjgjxy</code>] --偏移量=5--> B[密文：<br><code>pythonisthebest</code>]
```

### 相關函式
- `ord()`：把字母變成 ASCII code  
- `chr()`：把 ASCII code 變成字母  

### 範例程式
#### 凱薩加密
```python=
def caesar_encrypt(text: str, shift: int):
    result = ''
    for ch in text:
        if 'A' <= ch <= 'Z':
            result += chr((ort(ch) - ord('A') + shift) % 26 + ord('A'))
        elif 'a' <= ch <= 'z':
            result += chr((ort(ch) - ord('a') + shift) % 26 + ord('a'))
        else:
            result += ch

key = int(input('Please input the shift: '))
msg = input('Please input the message: ')
cipher = caesar_encrypt(msg, key)
print('密文:', cipher)
            
```
#### 凱薩解密
```python=
def caesar_decrypt(cipher_text: str, shift: int):
    return caesar_encrypt(cipher_text, -shift)

key = int(input('Please input the shift: '))
msg = input('Please input the message: ')
cipher = caesar_decrypt(msg, key)
print('明文:', cipher)

```

### Lab03：
Caesar Cipher Encrypter / Decrypter
#### Sample Input
case 1:
```
encrypt HelloWorld 5
```
case 2:
```
decrypt OlssvDvysk 7
```

#### Sample Output
case 1: 
```
密文： MjqqtBtwqi
```
case 2: 
```
明文： HelloWorld
```

### Lab - 03 提示
1. 獲取使用者輸入
2. 判斷功能
3. 運算後輸出對應資訊

### Lab04
Caesar Cipher Shift Counter
#### Sample Input
case 1:
```
MjqqtBtwqi
HelloWorld
```
case 2:
```
OlssvDvysk
HelloWorld
```

#### Sample Output
```
case 1: The shift is 5
case 2: The shift is 7
```

### Lab - 04 提示
1. 獲取使用者輸入
2. 執行字串判斷
3. 判斷直到獲取正確偏移量

### Lab05
Caesar Cipher Function Debug

```python
encrypted_flag = "UPZYH{wFao0uJhLzhYjyfWa}"

def caesar_decrypt(s, shift):
    result = ""
    for i in range(len(s)-1,0,-1):
        c = s[i]
        if 'a' <= c <= 'z':
            result += chr((ord(c) - ord('a') + shift) % 26 + ord('a'))
        elif 'A' <= c <= 'Z':
            result += chr((ord(c) - ord('A') + shift) % 26 + ord('A'))
        else:
            result += c
    return result

print("Decrypted:", caesar_decrypt(encrypted_flag, 7))

```




---
###### tags: `2025 NISRA Enlightened`
<style>
.navbar-brand::after { content: " × NISRA"; }
</style>