owned this note changed 4 years ago
Published Linked with GitHub

(學弟們有帶電腦的要裝python,建議裝個IDE,推薦用visual studio code或visual studio2019)

Python 第二週講義

林德恩、陳睿倬 Oct 15,2021

tags:python tcirc39th 社課 臺中一中電研社

電研社

社網:tcirc.tw
online judge:judge.tcirc.tw
IG:TCIRC_39th


None

None是一個值代表沒有值,但還是佔一個位子。
※不是空白


容器型態

容器是用來儲存多個變數用。
而部分的容器都有序號
而編號從0開始


字串也可以算是一種容器,所以可以指定位址。

字串變數[編號]

清單(Lists)

可儲存不同型態的元素,也可修改裡面元素(可把它想成書櫃)

#list名稱 = [元素1, 元素2, 元素3...] arr = [1, 2, 4, string, 7, True, 0.9]

訪問元素

如果想要知道特定list中第幾個元素
idx(序號) 0 1 2 3 4
list = [1, 6, 7, 3, 8]

arr = [1, 2, 4, string, 7, True, 0.9] print(arr[0]) # 注意: list的第一個元素的序號為0

output

1

append()

若要增加元素,則使用append()功能
會加到最後面

arr = [1, 2, 4, "string", 7, True, 0.9] print(arr) arr.append(5) arr.append("txt") print(arr)

output

[1, 2, 4, 'string', 7, True, 0.9]
[1, 2, 4, 'string', 7, True, 0.9, 5, 'txt']

pop()

若要刪除元素,則使用pop功能

arr = [1, 4, 3, 2, 6] print(arr) arr.pop(2) # 刪除序號為四的元素,後面元素往前遞補 print(arr) arr.pop() # 若無輸入序號,則刪除最後一項 print(arr)

output

[1, 4, 3, 2, 6]
[1, 4, 2, 6]
[1, 4, 2]

len()

arr = [1, 3, 4, 2, 6] print(len(arr))

output

5

clear()

clear()功能能清除list內的所有元素

arr = [1, 3, 4, 2, 6] print(arr) arr.clear() print(arr)

output

[1, 3, 4, 2, 6]
[]

insert()

若要插入元素至list的特定位置,則使用insert功能
使用方法為insert(序號, 要插入的東西)

arr = [1, 3, 4, 2, 6] print(arr) arr.insert(1, 5) print(arr)

output

[1, 3, 4, 2, 6]
[1, 5, 3, 4, 2, 6]

index()

若要搜尋list內的特定元素在第幾個序號,則使用index()功能
index(要查詢的元素)
!!注意,搜尋的值必須確定存在於list裡,否則會程式會顯示錯誤

arr = [1, 3, 4, 2, 6] print(arr) idx = arr.index(4) print(idx)

output

[1, 3, 4, 2, 6]
2

錯誤示範

arr = [1, 3, 4, 2, 6] print(arr) idx = arr.index(7) print(idx)

output

[1, 3, 4, 2, 6]
Traceback (most recent call last):
  File "<string>", line 3, in <module>
ValueError: 7 is not in list

sort()

若要對list內的元素進行排序,則使用sort()功能
!!注意如果要使用sort功能,list內的不可有數字和字串並存

arr = [1, 6, 3, 8, 5.6] print(arr) arr.sort() print(arr)

output

[1, 6, 3, 8, 5.6]
[1, 3, 5.6, 6, 8]

字串排序

arr = ['a', 'o', 'd', 'e' ] print(arr) arr.sort() print(arr)

output

['a', 'o', 'd', 'e']
['a', 'd', 'e', 'o']

空list可以直接用:

ls=list() #lists

字典(Dictionaries)

功能類似list,但元素無序號。取而代之的是key,key值須自己設定,且不能有重複key值(但可有重複元素)
數字、字串、元組(tuple)皆可作為key

""" dict = { key1 : value1 key2 : value2 . . . } """ dic = { "year" : 1992, "name" : "???" } print(dic["name"]) dic["name"] = "tcfsh" #修改key所對應的值 print(dic["name"]) dic["type"] = "senior_highschool" #新增一個key和其對應的值 print(dic["type"])

output

???
tcfsh
senior_highschool

其他型態的key

dic = { 1:5, "six":6, (1, 4):8 } print(dic)

output

{1: 5, 'six': 6, (1, 4): 8}
{1: 5, 'six': 6, (1, 4): 8}

clear()

功能和list的clear()功能一樣,清空字典裡的所有元素

dic = { "year" : 1992, "name" : "???" } print(dic) dic.clear() print(dic)

output

{'year': 1992, 'name': '???'}
{}

pop()

功能和list一樣,刪除特定元素的key和對應的值
pop(要刪除的key)

dic = { "year" : 1992, "name" : "???" } print(dic) dic.pop("year") print(dic)

ouput

{'year': 1992, 'name': '???'}
{'name': '???'}

空字典可以直接用:

dn=dict() #dictionanries

集合(Sets)

在python裡,集合是一個無順序的容器,且不能儲存重複元素

myset = {"apple", "banana", "cherry"} print(thisset)

output

{'cherry', 'banana', 'apple'}

add()

若要增加元素至set裡,用add()功能

myset = {"apple", "banana", "cherry"} print(myset) myset.add("mango") print(myset)

output

{'apple', 'banana', 'cherry'}
{'mango', 'apple', 'banana', 'cherry'}

空sets可以直接用:

st=set() #sets

元組(Tuple)

功能和list類似,但初始化後便不能再更改

#tuple名稱 = (元素1, 元素2....) mytuple = (1, "banana", True)

空元組可以直接用:

tp=tuple() #tuple

分割

split函式(部分功能說明)
因為python沒有內建同行以空白分隔兩個值,而且很多題目都需要用到這個功能,所以說明一下python如何處理。

要分割的文字變數.split("要判斷分割的符號") #括號內不加任何東西就預設為空白

使用

容器 或 多個變數(要和分割結果一樣多) = 要分割的變數.split("要判斷分割的符號") #推薦使用容器

※因分隔前是文字,所以分割後也是文字


程式

a = [None] i = input() a = i.split() print(a)

同行輸出

print(要輸出的內容,end='間格') #間隔可以沒東西 #間隔是會在句尾輸出

程式:

for i in range(10): print(i,end='=')

output:

0=1=2=3=4=5=6=7=8=9=

運算子

+&-&×&÷&次方&取餘(%)&取商(//)


比較運算子

用於判斷是否達成條件,結果為布林值


=(==)

兩個值是否相等
= 是定義資料的值

資料==資料

≠(!=)

兩個值是否不相等

資料!=資料

>、<、≥(>=)、≤(<=)

數值>數值 數值<數值 數值>=數值 數值<=數值

範例

print("123"=="345") print("1234"!="1234") print(1>2) print(1<=2)

output

False
False
False
True

邏輯運算子

and(且): 布林值 and 布林值
or(或):布林值 or 布林值
not(非):not 布林值


print(True and False) print(True or False) print(not False)

output

False
True
True

位元邏輯運算子

logic shift
將其二進為表示的數字左移或右移n位

數值<<n 數值>>n

&(and位元運算)
將兩個數值的二進位數值進行and運算

數值&數值 #10&01 == 00

|(or位元運算)
將兩個數值的二進位數值進行or運算

數值|數值 #10|01 == 11

~(not位元運算)
將其二進位數值進行not運算

~數值 #因python是用二補負法做正負判斷 #所以0(假設是000)進行not運算會變-1(111) #二補負法不會因儲存的位元不同而使not運算結果改變

^(xor位元運算)
將兩個數值的二進位數值進行xor運算

數值^數值 #10^11 == 01

二補負法:
設有3bit的空間
000→0
011→3
到一半時(1後全為0)轉為最小的負數繼續加一
100→-4
111→-1
優點:可以直接進行加減


範例程式

logic = True #1 number = 39 #100111 print(logic << 3) number = number >> 2#1001 print(number) print(3|9)#11 1001 print(~6)

output

8
9
11
-7

運算式

任何可以取得值的程式碼,都可以稱為運算式。


條件運算式

在判斷值為True或False後決定要執行的程式


if
是否達成條件,若有,則執行下方程式

if (條件): #coding

else

前面要先有 if 函式
未達成上方if的條件時,執行下方程式

if (條件): else: #coding

elif(else if)

前面要先有 if 函式
未達成上方if的條件時,判斷是否達成此條件,若有,執行下方程式

if (): #coding elif (): #coding elif (): #coding else: #coding

三元運算子
和if else功能差不多,但程式碼較短(一行)
可以連用

達成條件後執行 = if 條件 else 否則執行

switch
判斷指定條件,依照不同結果執行不同程式

switch(變數或運算式) { case 條件的結果1: //是冒號 程式; break; //一定要加,否則會繼續往下執行 case 條件的結果2: 程式; break; default: //其他 程式 break; }

python沒有switch


程式

a=0 b=1 if(a==b): print(a) elif(a<b): print(b) else: print("123456")

output

1

練習

b012: 不及格的危機


迴圈

迴圈是用來進行重複執行時的工具,它在不符合指定的條件前,除非強制跳出否則不會停止。


while

while會重複執行到條件達成為止。

while (條件): 程式

for

for迴圈也會重複執行到條件達成為止,但它可以直接設定次數。

for 變數 in 有編號的容器 或 range函數

變數可以不用先設定,而每次for迴圈開始就會加一。
變數的值會因後方的變數而改變。


使用range函數

for 變數 in range(起始值, 終止值, 公差): #變數會從起始值開始 #coding

range函數

range(起始值,終止值,差) #只能輸入整數型態 #起始值可不寫(起始值會為0) #差可不寫(差會為1)

使用容器

for 變數 in 字串: #因為字串也是容器一種 程式 或 for 變數 in list: #只要有序號的容器 程式

程式

s=[4,5,6,"a","b"] for i in range(-1,10,3): print(i) for k in "list": print(k) for n in s: print(n) for x in range(0,5): for y in range(x): print(y)

output

-1
2
5
8
l
i
s
t
4
5
6
a
b
0
0
1
0
1
2
0
1
2
3

break

跳出當前迴圈

迴圈 break

continue

會跳過後方要執行的程式從迴圈最上方的程式開始

迴圈 程式 #可寫可不寫 continue 程式 #會被跳過

程式

for i in range(0,5,1): print('1') if(i>3): continue print('2') a=0 print("-------") while(a<5): a+=1 b=0 while(b<3): b+=1 print(str(a)+str(b)) if(a==2): print("-------") break

output

1
2
1
2
1
2
1
2
1
-------
11
12
13
21
-------
31
32
33
41
42
43
51
52
53

練習
b036: 物種豐富度
Ans

Select a repo