python1
# Python基礎

[https://reurl.cc/WGEYk7](https://reurl.cc/WGEYk7)
[0. 輸出函數print()](#輸出數print())
[0-2. 輸入函數input()](#輸入函數input())
[1. 變數與資料型態](#變數與資料型態)
[2. 運算子](#運算子)
[3. 輸入與輸出](#輸入與輸出)
[4. 判斷結構if](#判斷結構if)
[5. 重複結構](#重複結構)
## *輸出函數print()*
* 語法:print()
* 例如:

<details>
<summary>語法:print(項目1[,項目2,...,sep=' ',end='\n'])</summary>
* 項目1,項目2,...:一次可以列印多個項目,中間用半型逗號隔開。
* sep: 分隔字元,列印多個項目,項目間以分隔字元區隔,預設為空白字元。
* end: 結束字元,列印結束時預設會加入換行符號("\n")。
</details>
<details>
<summary>print列印格式</summary>
1. f格式
name='Tom'
age=16
print(f'{name}今年{age}歲')
輸出:Tom今年16歲
2. %格式
name='Tom'
age=16
print(f'%s今年%d歲'%(name,age))
%s:字串, %d:整數, %f:浮點數
2. format格式
name='Tom'
age=16
print('{:s}今年{:d}歲'.format(name,age))
%s:字串, %d:整數, %f:浮點數
</details>
## *輸入函數input()*
* 語法:input(),有傳回值
* 例如:

* 輸出結果:

**兩個整數相加**
```python=
a=int(input()) #input()傳回字串型態,使用int函數將字串(數字)轉換成整數
b=int(input())
print(a+b)
""""
輸入
2
3
輸出
5
"""
```
```python=
#輸入一列資料,中間以空白隔開
a,b=input().split()
a,b=int(a),int(b)
print(a+b)
""""
輸入
2 3
輸出
5
"""
#另解
a=input().split() #串列list型態
ans=0
for i in range(len(a)):
ans+=int(a[i])
print(ans)
#另解 2
a=input().split()
ans=0
for i in a:
ans+=int(i)
print(ans)
#另解 3
a=list(map(int,input().split())) #轉換成整數int
ans=0
for i in a:
ans+=i
print(ans)
#另解 4
a=[int(i) for i in input().split()] #轉換成整數int
ans=0
for i in a:
ans+=i
print(ans)
```
map(<font color=red>int</font>,input().split()), 將串列list內的元素轉換成<font color=red>整數</font>型態;最後使用list函數,將map型態轉換成list型態。
## *變數與資料型態*
### 變數
變數:儲放資料的容器,就像馬克杯一樣。
命名規則:第一個字不能為數字,特殊符號僅接受底線_,大小寫視為不同,也接受中文字。
<style>
.wrap{max-width:100px;word-wrap:break-word;
}
</style>
|11|22|
|---|---|
|<div class="wrap">11.ww.rr rr ee ee ee de</div>|op|
### 資料型態
| 型別 | 名稱 |
| -------- | -------- |
| int | 整數 |
| float | 浮點數 |
| str | 字串 |
| bool | 布林值 |
```python=
a = 10 # 宣告a變數為整數型別
b = 3.14 # 浮點數
c = "hello" # 為字串型別, 單引號'hello'或雙引號"hello"皆可以。
d = True # 布林值
```
### 資料型別的轉換
```python=
a=float("3.14") # 3.14 字串型態轉成浮點數
b=int("101") # 101 字串型態轉成整數
c=str(3.14) # "3.14" 數值型態轉成字串
```
## *運算子*
| 算數運算子 | 意義 | 關係運算子 | 意義 | 邏輯運算子 | 意義 |
| ---------- | ---- | ---------- | ---- | ---------- | ---- |
| + | 加法 | > | 大於 | and | 且(True and True為True,其他為False) |
| - | 減法 | >= | 大於或等於 | or | 或(False or False為False,其他為True) |
| * | 乘法 | == | 相等 | not | 相反(非)not False為True |
| / | 除法 | != | 不相等 | | |
| // | 整數除法 | // | 小於 | | |
| % | 取餘數 | <= | 小於或等於 | | |
| ** | 指數 | | | | |
※<font color=red><b>注意「=」與「==」意義不同</b></font>
> * 「=」:指派符號(assign),將右側的結果,指定給左側的變數。
> * 「==」:判斷左右兩側是否相等。
```python=
a = 5/3 # 標準除法 =1.6666666666666667
a = 5//3 # 整除取商
a = 5 % 3 # 整除取餘數
b = 5 == 3# False,5與3相等,是錯的
b = 5 != 3# True,5與3不相等,是對的
a = b = 100 # 將100分別指派給a和b
c , d = 6 , 8 # 將6指派給c,8指派給d
e= (c <d ) and c != d #False, and的兩邊均為真,結果為真。比較運算子「<或…」會先執行,再執行邏輯運算子「and,or...」,若使用括號,則此會最優先執行。
e= not( d>c ) # False。先判斷「d>c」為真,因在前面加入「not」,結果為「非真」即假。
```
## 字串
參考
https://www.runoob.com/python/python-strings.html
```python=
print('hello'+'hi') # 'hellohi'
print('hi'*3) # 'hihihi'
print(len('apple')) # 5
```
c='Apple'
| 名稱 | H | e | l | l | o |
| --- |---|---|---|---|---|
| 索引 | 0| 1 | 2 | 3 | 4 |
| 索引 | -5 | -4 | -3 | -2 | -1 |
* Slice
單一字元
c[0] # 'A'
c[3] # 'l'
c[-1]# 'e'
c[-2] # 'l'
子字串
c[0:2] # 'App'
c[ :2] # 'App'
c[1:3] # 'pp'
c[3:5] # 'le'
c[3: ] # 'le'
c[ : ] # 'Apple'
c[::2] # 'Ape'
c[::-1]# 'elppA'
* find() & rfind()
語法: s.find(substring [,beg [,end]])
s='Apple'
s.find('A') # 0
s.find('p') # 1
s.rfind('p') # 2
s='This is a book.'
s.find('is') # 2
s.find('is',3) # 5
* replace()
語法:s.replace(old,new [,count]) #count取代幾個
s='This is a book.'
new=s.replace('is','IS') # 'ThIS IS a book.'
* count(key,[,beg [,end]])
s='This is a book.'
print(s.count('is')) # 2
```python=
a="hi"
b="good"
print(a*3)
print(a+b)
"""
輸出結果
hihihi
higood
"""
```
| 運算元 | 描述 | 實例 |
| :-----| :---- | :---- |
| + | 字串連接 | 单元格 |
| * | 重複字串 | "hi"*3 => "hihihi" |
| [] | 索引 | a="hello" a[1] => "e" |
| [:] | 子字串 | a="hello" a[2:4]=> "ll" |
| in | <div class="wrap">判斷是否存在於字串內</div> | "h" in "hello" => True|
| not in | <div class="wrap">判斷是否不存在於字串內</div> | "h" not in "hello" => False|
| 方法<img width=20> | 描述 |實例 |
| :-----| :---- | :---- |
| string.capitalize() | 將字串第1個字改為大寫 | "hello".capitalize() => "Hello" |
| string.upper() | 將字串全部改為大寫 | "hello".upper() => "HELLO" |
| string.lower() | 將字串全部改為小寫 | "HELLO".lower() => "hello" |
| string.count(str,[beg[,end]]) | 返回str在string出現的次數,如果left與right指定,即範圍 | "hello".count("l") => 2 |
| string.find(str,[beg[,end]]) | 尋找str是否在字串中 | "hello".find("l") => 2 |
| string.rfind(str,[beg[,end]]) | 尋找str是否在字串中(從後往前找) | "hello".rfind("l") => 3 |
| string.replace(str1,str2,[count]) | 將字串中的str1取代成str2, 如果指定count,則取代不超過count次 | "hello".replace("l","L") => "heLLo" |
| string.split() | 將字串分割切片成為串列 | "2,3,4".split(',') => ["2","3","4"] |
| string.join(List) | 以string為分隔符號,將串列中(字串元素)合併為一個新的字串 | "*".join(["6","7","8"]) => "6*7*8"|
| max(string) | 找出最大的Ascii碼字元 | max("hello") => "o" |
| min(string) | 找出最小的Ascii碼字元 | min("hello") => "e" |
| len(string) | 計算string的字元數長度 | len("hello") => 5 |
## 串列List
a=['red','green','blue','yellow','pink','white','black']
| 元素 | red | green | blue | yellow | pink | white | black |
| --- | --- | --- | --- | --- | --- | --- | --- |
| 索引 | 0| 1 | 2 | 3 | 4 | 5 | 6 |
| 索引 | -7 | -6 | -5 | -4 | -3 | -2 | -1 |
print(a[0],a[1],a[2]) #red green blue
print(a[-1],a[-2],a[-3]) #black white pink
`[:]`
print(a[2:4]) #['blue','yellow']
| 運算元 | 描述 | 實例 | 結果 |
| :-----| :---- | :---- | :---- |
| + | 組合 | [1,2,3]+[4,5,6] | [1,2,3,4,5,6] |
| * | 重複 | ['hi']*3 | ['hi','hi','hi'] |
| [] | 索引 | a=[1,2,3] | print(a[0]) # 1 |
| [:] | 子串列 | a=[1,2,3] | print(a[1:]) #[2,3]
| in | 存在 | 3 in [1,2,3] | True |
| not in | 不存在 | 3 not in [1,2,3] | False |
| 方法 | 描述 |實例 |
| :-----| :---- | :---- |
| list.append(obj) | 在串列末端加入元素 | a=[1,2];a.append(3) #[1,2,3] |
| list.count(obj) | 統計某個元素在串列中出現的次數 | [1,2,3,3].count(2) #2 |
| list.extend(seq) | 於串列的末端加入另一個串列seq | [1,2,3].extend([4,5]) #[1,2,3,4,5] |
| list.index(obj) | 找出第1個符合的索引值 | [5,6,7,8].index(7) #2 |
| list.insert(index,obj) | 插入元素於指定的索引 | [5,6,7,8].insert(1,100) #[5,100,6,7,8] |
| list.pop(index=-1) | 省略則移除串列最末一元素,也可指定索引值 | [1,2,3,4].pop()#[1,2,3]<br>[1,2,3,4].pop(2)#[1,2,4] |
| list.remove(obj) | 移除串列中第一個指定的元素 | [5,4,5,6].remove(5) #[4,5,6] |
| list.reverse() | 反向串列中的元素 | [4,6,5].reverse() #[5,6,4] |
| list.sort(key=None<br>,reverse=False) | 排序 | [4,6,5].sort(reverse=False) #[6,5,4] |
| list.clear() | 清空串列 | [] |
| list.copy() | 複製串列 | a=[1,2];b=a.copy() |
## 多鍵排序 lambda
```
lists = [(2, 5), (2, 3), (1, 2), (4, 2), (3, 4)]
lists.sort(key=lambda x: (x[0], x[1]))
print(lists)
#排序:二維串列依第1個元素遞增排序,若相同再依第2個元素遞增排序
#[(1, 2), (2, 3), (2, 5), (3, 4), (4, 2)]
```
```
lists = [(2, 5), (2, 3), (1, 2), (4, 2), (3, 4)]
lists.sort(key=lambda x: (-x[0], x[1]))
print(lists)
#排序:二維串列依第1個元素遞減排序,若相同再依第2個元素遞增排序
#[(4, 2), (3, 4), (2, 3), (2, 5), (1, 2)]
data = [
{'name': 'Alice', 'age': 30, 'city': 'New York'},
{'name': 'Bob', 'age': 25, 'city': 'Los Angeles'},
{'name': 'Charlie', 'age': 30, 'city': 'Chicago'},
{'name': 'David', 'age': 25, 'city': 'New York'}
]
# 按照年齡升序排序,年齡相同按照姓名降序排序
sorted_data = sorted(data, key=lambda x: (x['age'], -ord(x['name'][0])))
#字典排序
dic = {'banana':10, 'grape':20, 'apple':20, 'tomato':15, 'kiwi':6}
dic1 = sorted(dic.items(), key= lambda x:x[1] ) #預設 reverse=False 遞增排序
dic2 = sorted(dic.items(), key= lambda x:(x[1],x[0]), reverse = True)#兩鍵,皆遞減,x[0]為字串,可排序
dic3 = sorted(dic.items(), key= lambda x:(x[1],-ord(x[0][0])), reverse = True)#兩鍵的排序方式不同,可用負號,
# 但字串直接用負號產生錯誤,必須轉換成ord數字編碼再加負號即可
print(dic1) # [('kiwi', 6), ('banana', 10), ('tomato', 15), ('grape', 20), ('apple', 20)]
print(dic2) # [('grape', 20), ('apple', 20), ('tomato', 15), ('banana', 10), ('kiwi', 6)]
print(dic3) # [('apple', 20), ('grape', 20), ('tomato', 15), ('banana', 10), ('kiwi', 6)]
```
## 集合 set()
a={1,2,3,4}
b={3,4,5,6}
| 方法 | 描述 |實例 |
| :-----| :---- | :---- |
| \| | 聯集 | a \| b =>{1,2,3,4,5,6}|
| & | 交集 | a & b =>{3,4}|
| - | 差集 | a - b =>{1,2} |
| ^ | 互斥 | a ^ b =>{1,2,5,6} |
| 方法 | 描述 |實例 |
| :-----| :---- | :---- |
| s.add(obj) | 增加元素 | |
| s.remove(obj) | 刪除元素,若無此元素則產生錯誤訊息 | |
| s.discard(obj) | 刪除元素,若無此元素不會產生錯誤訊息 | |
| len(s) | 計算個數 | |
| s.clear() | 清空 | |
| s.copy() | 複製 | |
| s.union(set1,set2...) | 計算多個集合的聯集 | a={1,2,3}<br>b={2,4,5}<br>c={6,7,2}<br>ans=a.union(b,c)<br>print(ans)<br>{1, 2, 3, 4, 5, 6, 7} |
| s.intersection(set1,set2,...) | 計算多個集合的交集 | a={1,2,3}<br>b={2,4,5}<br>c={6,7,2}<br>ans=a.intersection(b,c)<br>print(ans)<br>{2} |
| s.difference(set1,set2,...) | 計算多個集合的差集 | a={1,2,3}<br>b={2,4,5}<br>c={6,7,2}<br>ans=a.difference(b,c)<br>print(ans)<br>{1,3} |
| s.update() | 添加元素 | a={1,2}<br>print(a)#{1,2}<br>a.update([3,4])<br>print(a)#{1,2,3,4}<br>a.update([5,6],[7,8])<br>print(a)##{1,2,3,4,5,6,7,8}<br>a.update((9,10))<br>print(a){1,2,...,9,10}<br>a.update({'a':'apple','b':'ball'})<br>print(a){1,2,...,9,10,'a','b'} |
| x.issubset(y) | x的所有元素是否包含於y的集合 | |
| x.issuperset(y) | y的所有元素是否包含於x的集合 | |
```
a={1,2,3,4}
b={3,4,5,6}
print(a|b) # 聯集
print(a & b) # 交集
print(a-b) # 差集
print(a^b) # 互斥
```
## *判斷結構if*
```python
#單向
if 條件(布林值):
程式區塊
#雙向
if 條件:
程式區塊
else: #上述不符合,則執行下方
程式區塊
#多向
if 條件:
程式區塊
elif 條件:
程式區塊
...
else:
程式區塊
#巢狀
if 條件:
if 條件:
程式區塊
else:
程式區塊
else:
if 條件:
程式區塊
else:
程式區塊
```
※舉例
```python=
t=25
if t>=28:
print("開冷氣")
else:
print("心靜自然涼")
```
## *重複結構*
### for迴圈
> 語法:for 變數 in range([start,]end[,step]])
```python=
#例1
for i in range(5):
程式區塊
```
※range(5) =>形成[0,1,2,3,4]之數字串列<font color=red><b>(初值省略,預設為0;不包括5, 只取至末值5的前1個為4)</b></font>。依序指派給變數i,執行下方的程式區塊,共執行5次。
```python=
#例2
for i in range(2,5):
程式區塊
```
※range(2,5) =>形成[2,3,4]之數字串列<font color=red><b>(只取至末值5的前1個為4)</b></font>, 共執行3次。
```python=
#例3
for i in range(1,9,2):
程式區塊
```
※range(1,9,2) =>形成[1,3,5,7]之數字串列<font color=red><b>(範圍只取至末值9的前1個為8,增減值為2)</b></font>, 共執行4次。
```python=
#例4
for i in range(10,0,-2):
程式區塊
```
※range(10,0,-2) =>形成[10,8,6,4,2]之數字串列<font color=red><b>(範圍只取至末值0的前1個為1,增減值為-2)</b></font>, 共執行5次。
### while迴圈
> 語法:while 條件: #條件為True,才執行下方的程式區塊
### break 與 continue
```py=
from PyPDF2 import PdfFileWriter,PdfFileReader,PdfReader,PdfWriter
import io
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter,A4
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
import os
import time
# from pikepdf import Pdf
os.chdir('/content/') # Colab 換路徑使用
# pdfmetrics.registerFont(TTFont("SimSun","SimSun.ttf"))
packet=io.BytesIO()
can=canvas.Canvas(packet,pagesize=A4)
# can.setFont("SimSun",18)
can.drawString(500,800,"hello")
can.save()
packet.seek(0)
new_pdf=PdfReader(packet)
existing_pdf=PdfReader(open('235.pdf',"rb"))
output=PdfWriter()
page=existing_pdf.pages[0]
page.merge_page(new_pdf.pages[0])
output.add_page(page)
outputStream=open("ot.pdf","wb")
output.write(outputStream)
outputStream.close()
```
完整版
```py=
# 1、合併多個pdf
# 2、分別於單獨的pdf的第1頁的左上角,加入「檔名」,再依序合併成1個新的pdf檔案。
# 3、中文需下載字型檔案SimSun.ttf,放置於程式執行的位置
# !pip install pikepdf
# !pip install pypdf2
# !pip install reportlab
import os
import time
from pikepdf import Pdf
from google.colab import drive
from PyPDF2 import PdfFileWriter,PdfFileReader,PdfReader,PdfWriter
import io
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter,A4
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
#因為[SimSun.ttf]字型檔案,放置[/content]目錄下,先註冊
os.chdir('/content/') # Colab 換路徑使用
pdfmetrics.registerFont(TTFont("SimSun","SimSun.ttf"))
# 再切換至雲端硬碟
drive.mount('/content/drive')
os.chdir('/content/drive/MyDrive/0000-2/3') # Colab 換路徑使用
pList = os.listdir()
if 't1.pdf' in pList:pList.remove('t1.pdf')
pList.sort()
#print(files)
OUTPUT = Pdf.new()
title="113商技模擬賽 113_02"
for page in pList:
# ''' 加入文字
# pdfmetrics.registerFont(TTFont("SimSun","SimSun.ttf"))
packet=io.BytesIO()
can=canvas.Canvas(packet,pagesize=A4)
can.setFont("SimSun",12)
can.drawString(500,800,"題號:"+page[:-4])
can.setFont("SimSun",12)
can.drawString(200,800,title)
can.save()
packet.seek(0)
new_pdf=PdfReader(packet)
existing_pdf=PdfReader(open(page,"rb"))
output=PdfWriter()
PAGE=existing_pdf.pages[0]
PAGE.merge_page(new_pdf.pages[0])
output.add_page(PAGE)
outputStream=open("t1.pdf","wb")
output.write(outputStream)
outputStream.close()
pdf1 = Pdf.open(page)
t=Pdf.open("t1.pdf")
# t=Pdf.open(page)
OUTPUT.pages.extend(t.pages)
if len(pdf1.pages)>1:
OUTPUT.pages.extend(pdf1.pages[1:])
time.sleep(0.2)
OUTPUT.save('new.pdf')
```

# 快速鍵
https://reurl.cc/aLyyLl
快速鍵
Ctrl+C 複製
Ctrl+V 貼上
Ctrl+X 剪下
Home 回到最左
End 回到最右
Ctrl +A 全選
Shift+end
Shift+home
Ctrl+Home 回到左上角
Ctrl+End 回到最後頁
### 求質數
```python=
import math,time
def get_prime(n):
if n<=1:
return []
prime=[2]
limit=int(math.sqrt(n))
print('limit:',limit)
data=[i+1 for i in range(2,n,2)]
# `print(data)
while limit>=data[0]:
prime.append(data[0])
# print('prime:',prime)
data=[j for j in data if j %data[0]!=0]
# print('data:',data)
return prime+data
t0=time.time()
print(get_prime(200000))
print(time.time()-t0)
#0.13561153411865234
```
```python=
import time
tt=int(input())
t0=time.time()
for n in range(2,tt+1):
f=True
for i in range(2,int(n**0.5)+1):
if n%i==0:
f=False
break
if f:print(n,end=' ')
print()
print(time.time()-t0)
#0.8413538932800293
```
### color;print顏色
```
print('\033[31;1m'+"hello"+'\033[0m')
```

說明
\033:跳脫字元
[:開始字元
31:顏色碼(紅)
1m:1 粗體;m 結尾字元
0m:0 Reset;m 結尾字元
```python=
a=['\033[30;1m','\033[31;1m','\033[32;1m','\033[33;1m','\033[34;1m','\033[35;1m','\033[36;1m','\033[37;1m',
'\033[40;1m','\033[41;1m','\033[42;1m','\033[43;1m','\033[44;1m','\033[45;1m','\033[46;1m','\033[47;1m',
'\033[0m']
a0=['灰','紅','綠','黃','藍','粉紅','青','白']
for i in range(16):
if i%8==0:print()
print(a[i][2:4],a[i]+'hello'+a[-1],end=' ')
```

### 單行 if
```python=
print("A") if a > b else print("=") if a == b else print("B")
p='A+' if s>=90 else 'A' if s>=80 else 'B+' if s>=70 else 'B' if s>=60 else 'C' if s>=50 else 'D' if s>=40 else 'E'
```
### sys.stdin 讀入資料
```python=
#1
import sys
lines = sys.stdin.readlines()
# 去除每行結尾處換行字元 "\n"
lines = [l.rstrip() for l in lines]
print(lines)
#2
import sys
while True:
# 讀取單行資料
line = sys.stdin.readline()
print(f'{line=}')
if not line.strip():
break
line = line.rstrip()
print(line)
#輸入最後一行後,按ctrl+Z
```
### pdf合併
```python=
import os,time
from pikepdf import Pdf
os.chdir('./all/113_01')
fList=os.listdir('.')
pList=[fn for fn in fList if '.pdf' in fn]
pList.remove('output.pdf')
output = Pdf.new()
for page in pList:
t=Pdf.open(page)
tmp=t.pages
for i in tmp:
output.pages.append(i)
# time.sleep(1)
output.save('output.pdf')
```
## 串列之複製(1維、多維)
```python=
import copy
a=[[1,2],[2,3]]
# 多維複製(深層複製)
#方法1 copy.deepcopy
b=copy.deepcopy(a)
b[0][0]=201
print(f'多維複製(1):{a=},{b=}')
#方法2
c=eval(str(a))
c[0][0]=202
print(f'多維複製(2):{a=},{c=}')
#方法3
d=[row[:] for row in a]
d[0][0]=203
print(f'多維複製(3):{a=},{d=}')
print()
# 一維複製
g=[1,2,3]
w1=g.copy() #方法1
w2=g[:] #方法2
w3=g+[] #方法3
w4=[i for i in g] #方法4
w1[0]=101
w2[0]=102
w3[0]=103
w4[0]=104
print(f'一維複製(1):{g=},{w1=}')
print(f'一維複製(2):{g=},{w2=}')
print(f'一維複製(3):{g=},{w3=}')
print(f'一維複製(4):{g=},{w4=}')
```
執行結果
一、多維串列
1.原始串列a
2.共三個複製方法,產生b,c,d等串列,各自修改內容,再檢視內容
二、一維串列
1.原始串列g
2.共四個複製方法,產生w1,w2,w3,w4等串列,各自修改內容,再檢視內容
```
多維複製(1):a=[[1, 2], [2, 3]],b=[[201, 2], [2, 3]]
多維複製(2):a=[[1, 2], [2, 3]],c=[[202, 2], [2, 3]]
多維複製(3):a=[[1, 2], [2, 3]],d=[[203, 2], [2, 3]]
一維複製(1):g=[1, 2, 3],w1=[101, 2, 3]
一維複製(2):g=[1, 2, 3],w2=[102, 2, 3]
一維複製(3):g=[1, 2, 3],w3=[103, 2, 3]
一維複製(4):g=[1, 2, 3],w4=[104, 2, 3]
```