python1

Python基礎


https://reurl.cc/WGEYk7

0. 輸出函數print()
0-2. 輸入函數input()
1. 變數與資料型態
2. 運算子
3. 輸入與輸出
4. 判斷結構if
5. 重複結構

輸出函數print()

  • 語法:print()
  • 例如:

輸入函數input()

  • 語法:input(),有傳回值
  • 例如:
  • 輸出結果:

兩個整數相加

a=int(input()) #input()傳回字串型態,使用int函數將字串(數字)轉換成整數 b=int(input()) print(a+b) """" 輸入 2 3 輸出 5 """
#輸入一列資料,中間以空白隔開 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(int,input().split()), 將串列list內的元素轉換成整數型態;最後使用list函數,將map型態轉換成list型態。

變數與資料型態

變數

變數:儲放資料的容器,就像馬克杯一樣。
命名規則:第一個字不能為數字,特殊符號僅接受底線_,大小寫視為不同,也接受中文字。

11 22
11.ww.rr rr ee ee ee de
op

資料型態

型別 名稱
int 整數
float 浮點數
str 字串
bool 布林值
a = 10 # 宣告a變數為整數型別 b = 3.14 # 浮點數 c = "hello" # 為字串型別, 單引號'hello'或雙引號"hello"皆可以。 d = True # 布林值

資料型別的轉換

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
/ 除法 != 不相等
// 整數除法 // 小於
% 取餘數 <= 小於或等於
** 指數

注意「=」與「==」意義不同

  • 「=」:指派符號(assign),將右側的結果,指定給左側的變數。
  • 「==」:判斷左右兩側是否相等。
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

print('hello'+'hi') # 'hellohi' print('hi'*3) # 'hihihi' print(len('apple')) # 5

c='Apple'

名稱 A p p l e
索引 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

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
判斷是否存在於字串內
"h" in "hello" => True
not in
判斷是否不存在於字串內
"h" not in "hello" => False
方法
描述 實例
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"]) => "67*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]
[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
,reverse=False)
排序 [4,6,5].sort(reverse=False) #[6,5,4]
list.clear() 清空串列 []
list.copy() 複製串列 a=[1,2];b=a.copy()
  • sorted():多條件排序
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)]

集合 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}
b={2,4,5}
c={6,7,2}
ans=a.union(b,c)
print(ans)
{1, 2, 3, 4, 5, 6, 7}
s.intersection(set1,set2,) 計算多個集合的交集 a={1,2,3}
b={2,4,5}
c={6,7,2}
ans=a.intersection(b,c)
print(ans)
{2}
s.difference(set1,set2,) 計算多個集合的差集 a={1,2,3}
b={2,4,5}
c={6,7,2}
ans=a.difference(b,c)
print(ans)
{1,3}
s.update() 添加元素 a={1,2}
print(a)#{1,2}
a.update([3,4])
print(a)#{1,2,3,4}
a.update([5,6],[7,8])
print(a)##{1,2,3,4,5,6,7,8}
a.update((9,10))
print(a){1,2,,9,10}
a.update({'a':'apple','b':'ball'})
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

#單向
if 條件(布林值):
    程式區塊
#雙向
if 條件:
    程式區塊
else:  #上述不符合,則執行下方
    程式區塊
    
#多向
if 條件:
    程式區塊
elif 條件:
    程式區塊
    ...
else:
    程式區塊
    
#巢狀
if 條件:
    if 條件:
        程式區塊
    else:
        程式區塊
else:
    if 條件:
        程式區塊
    else:
        程式區塊

※舉例

t=25 if t>=28: print("開冷氣") else: print("心靜自然涼")

重複結構

for迴圈

語法:for 變數 in range([start,]end[,step]])

#例1 for i in range(5): 程式區塊

※range(5) =>形成[0,1,2,3,4]之數字串列(初值省略,預設為0;不包括5, 只取至末值5的前1個為4)。依序指派給變數i,執行下方的程式區塊,共執行5次。

#例2 for i in range(2,5): 程式區塊

※range(2,5) =>形成[2,3,4]之數字串列(只取至末值5的前1個為4), 共執行3次。

#例3 for i in range(1,9,2): 程式區塊

※range(1,9,2) =>形成[1,3,5,7]之數字串列(範圍只取至末值9的前1個為8,增減值為2), 共執行4次。

#例4 for i in range(10,0,-2): 程式區塊

※range(10,0,-2) =>形成[10,8,6,4,2]之數字串列(範圍只取至末值0的前1個為1,增減值為-2), 共執行5次。

while迴圈

語法:while 條件: #條件為True,才執行下方的程式區塊

break 與 continue

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()

完整版

# 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')

image

快速鍵

https://reurl.cc/aLyyLl

快速鍵
Ctrl+C 複製
Ctrl+V 貼上
Ctrl+X 剪下
Home 回到最左
End 回到最右
Ctrl +A 全選
Shift+end
Shift+home
Ctrl+Home 回到左上角
Ctrl+End 回到最後頁

求質數

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
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')

image
說明
\033:跳脫字元
[:開始字元
31:顏色碼(紅)
1m:1 粗體;m 結尾字元
0m:0 Reset;m 結尾字元

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=' ')

image