Contents

python基礎語法

Vars

1
2
3
4
5
6
7
8
auto1 = 2
int1 = int(2)
float1 = float(2.0)
string1 = str("Hello World")
bool1 = bool(1)
list1 = [1, 2, 3]
dict1 = {'A': 1, 'B': 2, 'C': 3}
tuple1 = (1, 2, 3)

String

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
print(string1.lower())    #>>>hello world
print(string1.upper())    #>>>HELLO WORLD
print(string1.index("W"))    #>>>6
print(string1.isupper())    #>>>False
print(string1.islower())    #>>>False

str1 = 'cls'
str2 = str1.translate({ord('l'):None})  #取代'l'為''
#以上等價於
str2 = str1.replace('l', '')            #取代'l'為''

對字串頭尾進行操作

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
s = "eesee"

print(s.removeprefix('e'))
print(s.removesuffix('e'))
print(s.strip('e'))
print(s.lstrip('e'))

>>> esee
>>> eese
>>> s
>>> see

List

remove() and pop()

remove()能移除list中對應的值,pop()則能移除list中對應的index。

1
2
3
4
5
6
7
8
arr = ['1', '2', '3']
print(arr.remove('1'))
>>> None
print(arr)
>>> [2, 3]
arr.pop(1)
print(arr)
>>> [2]

sort() v.s. sorted()

sort()

1
2
3
a = [2, 3, 1]
a.sort()
print(a)    #>>>[1, 2, 3]

sorted()

1
2
3
a = [2, 3, 1]
b = sorted(a)
print(b)    #>>>[1, 2, 3]

key

1
2
3
4
5
def key(n):
	return 0 if n == 3 else n

a = [2, 3, 1]
print(sorted(a, key=key))    #>>>[3, 1, 2]

Append v.s. Extend

1
2
3
list1 = [1, 2, 3]
list1.append(4)
list1.extend([4, 5, 6])

Dict

迭代

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
d = {'A': 1, 'B': 2, 'C': 3}
for i in d:
	print(i)
""">>>
A
B
C
"""

for i, j in zip(d.keys(), d.values()):
    print(i, j)
""">>>
A 1
B 2
C 3
"""

get()

在dict中存在get方法

1
2
3
4
5
6
7
mes = {
    'a': 1,
    'b': 2,
    'c': 3
}
print(mes.get('a'))    #>>>1
print(mes.get('d', 'can\'t find it'))    #>>>can\'t find it

Output

1
2
print(int1, string1)    #>>>2 Hello World
print()    #>>>\n

repr() and str()

兩者皆能傳回一個可打印字串,對於python的許多類別來說:1

  • str()傳回的是非官方的字串。
  • repr()傳回的是官方字串,多用於調適功能。2 間單來說,前者是使用者自定義,後者多會用於正式場合,會與官方格式保持一致性。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
a = 1
print(a)
#等價於
print(str(a))
#>>>1

print(repr(a))
#等價於python shell中的
>>>a
#>>>'1'

此外,repr()通常會與eval()相互可逆,也就是說,repr()回傳的字串傳入eval()函式後會回傳原有的值,反之亦同(此條規則次用於大部分的python基本類別)。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
a = '1'
print(repr(a))
#>>>'1'
a = eval(a)
print(a)
#>>>1
print(repr(a))
#>>>1
print(type(a))
#>>><class 'int'>

b = 1
print(eval(repr(b)))
#>>>1

Math

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import math

#n次方
print(pow(2,4))
#以上等價於
print(2**4)
#>>>16

#根號
print(math.sqrt(4))
#>>>2.0

#取最大、最小
print(max(4,2,5,6,8,5,6))    #>>>8
print(min(4,2,5,6,8,5,6))    #>>>2

#最大公因數
print(math.gcd(4,2))
#>>>2

#四捨五入float為int
print(round(4.4))    #>>>4
#無條件捨去
print(math.floor(4.9))    #>>>4
#無條件進位
print(math.ceil(4.1))    #>>>5

if

三元表達式(ternary conditional operator)

[True event] if [condition] else [false event]

1
2
3
4
a = [0, 1, 2]
for i in a:
    print(i) if i == 1 else 0
#>>>1

break

break語法會跳出迴圈。

continue

continue語法會跳過剩下的程式碼並開始下一段循環。

1
2
3
4
5
6
7
8
9
a = [0, 2, 9]
for i in a:
    if i == 0:
        print("Yes")
    else:
	    continue
	print(i)
#>>>Yes
#>>>0

pass

pass語法會繼續執行剩下的程式碼並開始下一段循環。3

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
a = [0, 2, 9]
for i in a:
    if i == 0:
        print("Yes")
    else:
	    pass
	print(i)
#>>>Yes
#>>>0
#>>>2
#>>>9

while

while語法的條件可以隨著迭代而更動。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
n = 0
l = [1, 2, 3]
while n < len(l):
    print("Hi")
    if n==1:
        l.append('j')
    n += 1
>>> Hi
>>> Hi
>>> Hi
>>> Hi

反之若為for,條件則無法隨著迭代更動。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
n = 0
l = [1, 2, 3]
for i in range(len(l)):
    print("Hi")
    if n==1:
        l.append('j')
    n += 1
>>> Hi
>>> Hi
>>> Hi

zip

zip為python的類別之一,能接收多的可迭代(iterable)物件並返回有序的列表(list)。

官方說明:

1
2
3
4
5
6
7
help(zip)
""">>>
zip(*iterables, strict=False) --> Yield tuples until an input is exhausted.
 |
 |     >>> list(zip('abcdefg', range(3), range(4)))
 |     [('a', 0, 0), ('b', 1, 1), ('c', 2, 2)]
 """

References