Python 30 天筆記

常用網頁

範例程式

Youtube

建議

Lists

Lists (array) 可存不同種類

1
2
3
4
5
6
7
8
list_var = ['some string' , 123, "another string"]
list_var.append("some other item") // 加入新 item
len(list_var) // 4 ( 4 個 item)
len("an string") // 9 ( 9 個字元)

list = [1,2,3]
list.pop(0)
print(list) // [2,3]

Dictionary

{} 包起來

1
2
3
4
5
6
7
8
9
// Python 可以用字串當作 Key
a_dict = { "a":"1", "b":"2", "c":"3"}
a_dict["abc"] = "another" // {'a': '1', 'b': '2', 'c': '3', 'abc': 'another'}

// Python 也可以用整數當作 Key
abc = {}
abc[0] = "abc"

// dic 也可以把 dic 或 list 放進去

Tuple

1
2
3
tup = ()
tup = ("abc","abc")
tup = ( ("a","b"), ("c","d"))

差別

Tuple 資料不可以修改,List 可以

但是 Tuple 使用的資料型態會比較小

Loop

1
2
3
4
5
6
7
8
9
10
11
bag = [1,2,3,4,5,6,7,8,9,10]

// For
for item in bag:
print(item)

// While
i = 0
while i < 11:
print("OK")
i+=1

Conditionals

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
True
Flase

i = 1
if i == 1:
print("A")
elif i == 2:
print("B")
else:
print("C")


print(isinstance(3, int)) # T
print(isinstance("Jason", int)) # F
print(isinstance("Jason", str)) # T

Function

1
2
3
4
5
6
7
8
9
10
11
12
13
str_items = ["A", "C", "W", "a", "E"]
str_items.sort()
str_items.sort(key=str.lower)
str_items.sort(key=str.lower,reverse=True)

int_items = [123,11,534.12,561,22.213]
new_items = sorted(int_items,reverse=True)
print(new_items)

int_items = [123,11,534.12,561,22.213]
new_items = sorted(int_items,reverse=True)
print(new_items)
print(sum(int_items))

自訂 function

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
27
28
29
30
items = ["Mac", "Phone", 123.11, 462.14, "Jason", "Bag", 512]

str_items = []
num_items = []

for i in items:
if isinstance(i, float) or isinstance(i, int):
num_items.append(i)
elif isinstance(i, str):
str_items.append(i)
else:
pass

print(str_items)
print(num_items)

def parse_lists(some_list):
str_list_items = []
num_list_items = []
for i in items:
if isinstance(i, float) or isinstance(i, int):
num_list_items.append(i)
elif isinstance(i, str):
str_list_items.append(i)
else:
pass
return str_list_items,num_list_items


print(parse_lists(items))

String

Cheat Sheet

1
2
3
4
5
6
7
8
9
10
11
text = "This is a {var}".format(var="cool")
print(text)

text = "{0} {1} {2}".format("A","B","C")
print(text)

text = "Hello %s %s" %("Jason","Sharon")
print(text)

text = "Hello %%s %s" %("Jason")
print(text) // Hello %s Jason