l = []
l.append(input())
l.append(input())
l.append(input())
print(l)
用迴圈可以改寫為
l = []
for i in range(3):
l.append(input())
print(l)
l = [1,4,7,9]
print(l[0])
print(l[1])
print(l[2])
print(l[3])
用迴圈可以改寫為
l = [1,4,7,9]
for i in range(0,3+1):
print(l[i])
或是改寫成更為簡潔的
l = [1,4,7,9]
for i in l:
print (i)
上面的程式碼執行起來的概念等同於
i=1 # 串列l的第1個元素
print(i)
i=4 # 串列l的第2個元素
print(i)
i=7 # 串列l的第3個元素
print(i)
i=9 # 串列l的第4個元素
print(i)
以range
迭代,雖然寫起來比較複雜,但彈性比較高
(eg.只想拿取奇數位置的元素)
l = [1,4,7,9]
for i in range(0,3+1):
print(l[i])
以串列迭代,雖然寫起來比較簡潔,但只能所有元素全部拿取
(eg.只想拿取奇數位置的元素,要另外在迴圈裡寫判斷式)
l = [1,4,7,9]
for i in l:
print (i)
# 定義函式
def 函式名稱(參數1,參數2,...):
程式碼
程式碼
程式碼
return 物件1,物件2,物件3
# 呼叫函式
函式名稱(引數1,引數2,...)
return
回傳可有可無(若無會回傳None
),用tuple
可回傳多個物件def 洗衣機():
注水
旋轉清洗
排水
旋轉脫水
def coffee_machine(coffie_type):
coffee = espresso
if coffie_type=="美式咖啡":
coffee+= water
elif coffie_type=="拿鐵":
coffee+= milk*2 + foam
elif coffie_type=="卡布奇諾":
coffee+= milk + foam
.
.
.
return coffee
cup = coffee_machine("拿鐵")
還記得我們使用過不少工具:print()
、ord()
、max()
...,
這些都是內建函式Bult-in Function,他們背後的運作原理可能像是這樣:
print(max([1,2,7,9,10]))
a=max([1,2,7,9,10])
print(a)
10 10
def my_max(data):
num_max = -999999999
for i in data:
if i>=num_max:
num_max = i
return num_max
print(my_max([1,2,7,9,10]))
10
def is_leap(year):
leap = False
...
你的程式碼
...
return leap
print(is_leap(2000))
print(is_leap(1800))
l = [["姿君",25],["Mars",20],["毛毛",10]]
for member in l:
if member[0]=="Mars":
member[1]+=15
for member in l:
if member[0]=="姿君":
member[1]+=5
print(l)
[['姿君', 30], ['Mars', 35], ['毛毛', 10]]
l = [["姿君",25],["Mars",20],["毛毛",10]]
def change_money(name,money):
for member in l:
if member[0]==name:
member[1]+=money
change_money("Mars",15)
a = change_money("姿君",5) # 這是一個沒有回傳值的函式
print(a)
print(l)
None [['姿君', 30], ['Mars', 35], ['毛毛', 10]]
目前程式中記錄著會員跟儲值金額,
已經寫好一個自行定義的Function:change_money
,
有一個大家加值記錄的文檔log
,請大家處理這份文檔,加值到程式中
答案是
[['姿君', 50], ['Mars', 35], ['毛毛', 20]]
l = [["姿君",25],["Mars",20],["毛毛",10]]
def change_money(name,money):
for member in l:
if member[0]==name:
member[1]+=money
log = """
Mars 15
姿君 5
姿君 20
毛毛 10
"""
...
你的程式碼
...
print(l)
原字串.split(子字串)
原字串.strip()
def f1():
print("f1")
def f2():
print("f2")
def f3():
print("f3")
d = {"apple":f1, "banana":f2, "orange":f3}
d["apple"]()
f1
b = 2 # global
def test():
a = 1 # local
print(a,b,len([3,4,5])) # local,global,built-in
test()
1 2 3
b = 2 # global
def test(a): # local
print(a,b,len([3,4,5])) # local,global,built-in
test(1)
1 2 3
雖然Python我們通常理解為一行行執行,
但在遇到函式時,他解析函式
b = 2 # global
def test(a): # local
print(a,b) # local,global?
b = a+1 # b=a+1 :指派名稱 b 給a+1 => 所以 b 是 local
test(1)
--------------------------------------------------------------------------- UnboundLocalError Traceback (most recent call last) <ipython-input-8-808bd44f8e1a> in <module>() 3 print(a,b) # local,global? 4 b = a+1 # b=a+1 :指派名稱 b 給a+1 => 所以 b 是 local ----> 5 test(1) <ipython-input-8-808bd44f8e1a> in test(a) 1 b = 2 # global 2 def test(a): # local ----> 3 print(a,b) # local,global? 4 b = a+1 # b=a+1 :指派名稱 b 給a+1 => 所以 b 是 local 5 test(1) UnboundLocalError: local variable 'b' referenced before assignment
a,b = 1,2 # global
def test(a,b):
len = 6 # local
print(a,b,len,"in function test") # local,local,local
test(3,4)
c = len([7,8,9]) # built-in
print(a,b,c) # global,global,global
3 4 6 in function test 1 2 3
a,b = 1,2 # global
def test(a,b):
len = 6 # local
print(a,b,len,"in function test") # local,local,local
print(len([7,8,9])) # error 因為 local 掩蓋掉 built-in
test(3,4)
3 4 6 in function test
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-10-072a24760387> in <module>() 4 print(a,b,len,"in function test") # local,local,local 5 print(len([7,8,9])) # error 因為 local 掩蓋掉 built-in ----> 6 test(3,4) <ipython-input-10-072a24760387> in test(a, b) 3 len = 6 # local 4 print(a,b,len,"in function test") # local,local,local ----> 5 print(len([7,8,9])) # error 因為 local 掩蓋掉 built-in 6 test(3,4) TypeError: 'int' object is not callable
a,b = 1,2
def test(a,b):
print(a,b,"in function test")
def temp(a,b):
print(a,b,"in function temp")
test(3,4)
temp(5,6)
3 4 in function test 5 6 in function temp
那要怎麼存取跨函式間的物件呢?
def change_money(name,money):
for member in l:
if member[0]==name:
member[1]+=money
def main():
l = [["姿君",25],["Mars",20],["毛毛",10]]
change_money("Mars",15)
change_money("姿君",5)
print(l)
main()
__
當作名稱前綴,方便維護 eg. __my_list
# 直接把物件宣告在全域
l = [["姿君",25],["Mars",20],["毛毛",10]]
def change_money(name,money):
for member in l:
if member[0]==name:
member[1]+=money
# 這裡面沒有重新指派名稱l,所以用的就是global的l
def main():
change_money("Mars",15)
change_money("姿君",5)
print(l)
main()
[['姿君', 30], ['Mars', 35], ['毛毛', 10]]
# 利用 global 把物件變成全域
def change_money(name,money):
for member in l:
if member[0]==name:
member[1]+=money
def main():
global l # 在使用前先宣告
l = [["姿君",25],["Mars",20],["毛毛",10]] # global l
change_money("Mars",15)
change_money("姿君",5)
print(l)
main()
[['姿君', 30], ['Mars', 35], ['毛毛', 10]]
# 可變物件
def change_money(name,money,l):
print (id(l),"in function origin")
for member in l:
if member[0]==name:
member[1]+=money
print (id(l),"in function after change")
def main():
l = [["姿君",25],["Mars",20],["毛毛",10]]
print (id(l))
change_money("Mars",15,l)
change_money("姿君",5,l)
print(l)
main()
139675831776648 139675831776648 in function origin 139675831776648 in function after change 139675831776648 in function origin 139675831776648 in function after change [['姿君', 30], ['Mars', 35], ['毛毛', 10]]
# 不可變物件
def add(x,y):
print(id(x),id(y),"in function origin")
x = x+1
y = y+2
print(id(x),id(y),"in function after change")
print(x,y)
def main():
x = 5
y = 10
print(id(x),id(y))
add(x,y)
print(x,y)
main()
10105952 10106112 10105952 10106112 in function origin 10105984 10106176 in function after change 6 12 5 10
# 不可變物件
def add(x,y):
x = x+1
y = y+2
print(x,y)
return x,y # 要記得回傳
def main():
x = 5
y = 10
x,y = add(x,y)
print(x,y)
main()
6 12 6 12
for i in range(1,5+1):
a=10
print(i,a)
5 10
# 所以如果你的物件名稱在迴圈中有用到,小心被修改到
i=1
for i in range(1,5+1):
a=10
print(i,a)
5 10
請告訴我出現最多的字母
s = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
unique_word_list=[]
max_count = 0
max_alpha = ""
for i in s:
if (ord(i) in range(ord("a"),ord("z")+1)) and (i not in unique_word_list):
unique_word_list.append(i)
# print (i,s.count(i))
if s.count(i) > max_count:
max_count = s.count(i)
max_alpha = i
print("{}是出現最多的字母,出現了{}次".format(max_alpha,max_count))
r是出現最多的字母,出現了18次
那如果想要知道出現次數前五名的? 難道要寫max_count1,max_count2,max_count3
...?
這時,排序就是個好方法,雖然會多花一點排序的計算資源,但排序後的應用非常值得!
(圖書館如果都不花時間整理書,相信借書的時候找書一定找得很辛苦)
simple_list = (1,5,3,4,2)
print(sorted(simple_list))
print(sorted(simple_list,reverse=True))
print(simple_list)
[1, 2, 3, 4, 5] [5, 4, 3, 2, 1] (1, 5, 3, 4, 2)
nested_list_number = [[5,4],[1,9],[1,7],[4,2]]
nested_list_string = [["Python",4],["Hello",6],["World",2],["PyLadies",2]]
print(sorted(nested_list_number))
print(sorted(nested_list_string))
[[1, 7], [1, 9], [4, 2], [5, 4]] [['Hello', 6], ['PyLadies', 2], ['Python', 4], ['World', 2]]
simple_list = [1,5,3,4,2]
print(simple_list.sort())
print(simple_list)
None [1, 2, 3, 4, 5]
simple_list = [1,5,3,4,2]
simple_list.sort(reverse=True)
print(simple_list)
[5, 4, 3, 2, 1]
def get_median(l):
排序
if len(l)%2==1:
return ...
else:
return ...
print(get_median([12,4,5,3,8,7]))
print(get_median([12,4,5,3,8]))
如果想要以第二個元素去排...
def my_sort(item):
return item[1]
def my_sort2(item):
return item[1],item[0] # 如果第二個元素一樣,則以第一個元素排序
nested_list_string = [["Python",4],["Hello",6],["World",2],["PyLadies",2]]
print(sorted(nested_list_string))
print(sorted(nested_list_string,key=my_sort))
print(sorted(nested_list_string,key=my_sort2))
[['Hello', 6], ['PyLadies', 2], ['Python', 4], ['World', 2]] [['World', 2], ['PyLadies', 2], ['Python', 4], ['Hello', 6]] [['PyLadies', 2], ['World', 2], ['Python', 4], ['Hello', 6]]
# 想要以第二個元素由大到小排序,如果相同則以第一個元素由小到大排序
def my_sort(item):
return item[1]
def my_sort2(item):
return -item[1],item[0] # 因為第二個元素剛好是數字,可以用負數處理
nested_list_string = [["Python",4],["Hello",6],["World",2],["PyLadies",2]]
print(sorted(nested_list_string,key=my_sort,reverse=True))
print(sorted(nested_list_string,key=my_sort2))
[['Hello', 6], ['Python', 4], ['World', 2], ['PyLadies', 2]] [['Hello', 6], ['Python', 4], ['PyLadies', 2], ['World', 2]]
利用字典.items()
取得所有鍵值與值的配對
def sort_by_value(item):
return item[1]
d = {"Python":4, "Hello":6, "World":2, "PyLadies":2}
print(sorted(d.items())) # items 第一個元素是鍵值key,所以預設以key排序
print(sorted(d.items(),key=sort_by_value))
[('Hello', 6), ('PyLadies', 2), ('Python', 4), ('World', 2)] [('PyLadies', 2), ('World', 2), ('Python', 4), ('Hello', 6)]
剛使用排序時, 發覺我們要指定排序算法、是否要翻轉排序的時候,
不是把我們的參數傳進去就好
sorted(nested_list_string,my_sort,True)
需要寫key=
、reverse=
sorted(nested_list_string,key=my_sort,reverse=True)
這種用法叫做「關鍵字參數」,可參考補充知識。
覺得之前練習題太少,很想要再多一些Python基礎語法的練習嗎?
以下提供幾個有趣的Python練習網站,也稍微選了一些可練習的題目參考(當然還有更多)
下一期的活動內容:網路爬蟲、Python 自動化的樂趣,
會帶領大家學習到更多的Python實戰經驗
CheckIO是利用呼叫函式,得到回傳值來測試答案,
所以請把程式碼寫在函式裡面,記得都要有回傳值,
也不要修改函式的名稱、傳遞的參數數量、回傳的參數數量。
當然 HackerRank 也有更難的Challenges題目,需要考慮效能
FIND THE RUNNING MEDIAN - 演算法例:會跑的中位數~改變人生從解題開始~ by 五倍紅寶石 tsw
HackerRank是利用input()
輸入資料,然後看print()
的結果來驗證答案,
所以有input()
的地方請不要改掉,
請將你的結果print出來,但請不要多print除了答案以外的東西。
有些可以直接寫在全域區域中(記得要縮排)
有些規定要用函式撰寫 成功畫面
+
運算元,數值.__add__
方法LeetCode大部分是利用呼叫函式,得到回傳值來測試答案,
所以請把程式碼寫在函式裡面,記得都要有回傳值,
也不要修改函式的名稱、傳遞的參數數量、回傳的參數數量。
(但有些會是原地修改,Run Code時會有提示)
測試結果 成功畫面
def f(x,y,z):
print(x,y,z)
f(1,2,3) # 位置參數
f(1,z=3,y=2) # 關鍵字參數,可不管順序
1 2 3 1 2 3
def f(x,y,z):
print(x,y,z)
f(1,2,3,4)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-28-525f5b13dc35> in <module>() ----> 1 f(1,2,3,4) TypeError: f() takes 3 positional arguments but 4 were given
f(1,2)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-29-c0c95413393f> in <module>() ----> 1 f(1,2) TypeError: f() missing 1 required positional argument: 'z'
def f(x,y,z):
print(x,y,z)
f(1,z=3,x=1,y=2)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-30-dd5e31b9a68b> in <module>() ----> 1 f(1,z=3,x=1,y=2) TypeError: f() got multiple values for argument 'x'
def f(x,y,z):
print(x,y,z)
f(z=3,y=2,1)
File "<ipython-input-31-b1c1fc708b60>", line 1 f(z=3,y=2,1) ^ SyntaxError: non-keyword arg after keyword arg
def f(x,y,z=3):
print(x,y,z)
f(1,2)
f(1,2,4)
1 2 3 1 2 4
remainder(20, 7) v.s. remainder(number=20, divisor=7)
參考2016年毛毛帶的Effective Python讀書會
def book_restaurant_for_dinner(location, hour=18):
print("Book '{}' successfully at {} PM.".format(location, hour))
book_restaurant_for_dinner("Maomao Pasta")
book_restaurant_for_dinner("Big Hamberger")
book_restaurant_for_dinner("BBQ Shop", hour=21)
Book 'Maomao Pasta' successfully at 18 PM. Book 'Big Hamberger' successfully at 18 PM. Book 'BBQ Shop' successfully at 21 PM.
def book_restaurant_for_dinner(location, hour=18, minute=0):
print("Book '{}' successfully at {}:{:0>2d} PM.".format(location, hour, minute))
# 舊函式呼叫 (不需修改)
book_restaurant_for_dinner("Maomao Pasta")
book_restaurant_for_dinner("Big Hamberger")
book_restaurant_for_dinner("BBQ Shop", hour=21)
# 新函式呼叫
book_restaurant_for_dinner("Abby Pasta", minute=30)
Book 'Maomao Pasta' successfully at 18:00 PM. Book 'Big Hamberger' successfully at 18:00 PM. Book 'BBQ Shop' successfully at 21:00 PM. Book 'Abby Pasta' successfully at 18:30 PM.
def f(x,y=2,z):
print(x,y,z)
f(1,z=3)
File "<ipython-input-35-0ed255af70d3>", line 1 def f(x,y=2,z): ^ SyntaxError: non-default argument follows default argument
在函式定義時將成為預設值的運算式只會被執行一次
得到物件後由函式物件記錄著,之後每次呼叫,只會得到之前的結果
a=3
def test(x,y=a):
print(x,y)
test(1)
a = 999
test(1)
1 3 1 3
def test(x,y=[]):
y.append(x)
print(y)
test(1)
test(2)
test(9,[5,7])
[1] [1, 2] [5, 7, 9]
def test(x,y=None):
if y == None:
y = []
y.append(x)
print(y)
test(1)
test(2)
test(9,[5,7])
[1] [2] [5, 7, 9]
*
:用tuple處理額外的位置參數¶def f(x,y,*arg):
print(x,y,arg)
f(1,2,3,4,5)
f(1,2)
1 2 (3, 4, 5) 1 2 ()
def f(x,y,*arg,a):
print(x,y,arg,a)
f(1,2,3,4,5,a=6)
1 2 (3, 4, 5) 6
def f(x,y=1,*arg,a=2):
print(x,y,arg,a)
f(1,2,3,4,5)
1 2 (3, 4, 5) 2
**
:用dict處理額外的關鍵字參數¶def f(x,y,**arg):
print(x,y,arg)
f(1,2,a=3,b=4,c=5)
1 2 {'a': 3, 'c': 5, 'b': 4}
def f(x,y,*arg1,**arg2):
print(x,y,arg1,arg2)
f(1,2,3,4,c=5)
1 2 (3, 4) {'c': 5}
def f(x,y,*arg1,a,b,**arg2):
print(x,y,a,b,arg1,arg2)
f(1,2,3,4,a=5,b=6,c=7)
1 2 5 6 (3, 4) {'c': 7}
*
:傳入可迭代物件¶def f(a,b,c,d,e):
print(a,b,c,d,e)
f(5,6,*range(3))
5 6 0 1 2
f(*range(3),d=5,e=6)
0 1 2 5 6
**
:傳入映射物件¶def f(a,b,c,d,e):
print(a,b,c,d,e)
d = {"c":1,"d":2,"e":3}
f(5,6,**d)
5 6 1 2 3
d = {"a":5,"c":1,"d":2,"e":3}
f(5,6,**d)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-48-004c09ae30e9> in <module>() 1 d = {"a":5,"c":1,"d":2,"e":3} ----> 2 f(5,6,**d) TypeError: f() got multiple values for argument 'a'
不論你是在打牌,或是整理圖書館架上的書、衣櫃裡的衣服,
都很常使用插入排序法 Insertion Sort。
def insert_sort(l):
n=len(l)
if n==1:
return l
for i in range(1,n):
for j in range(i,0,-1): # 已排好的序列
if l[j]<l[j-1]:
l[j],l[j-1] = l[j-1],l[j]
return l
print(insert_sort([6,7,8,1,2,3,5,4]))
[1, 2, 3, 4, 5, 6, 7, 8]
def insert_sort(l):
n=len(l)
if n==1:
return l
for i in range(1,n):
for j in range(0,i): # 已排好的序列
if l[i]<l[j]: # 只要比較小就插入,因為越往後越大
value = l[i]
l.pop(i)
l.insert(j,value)
return l
print(insert_sort([6,7,8,1,2,3,5,4]))
[1, 2, 3, 4, 5, 6, 7, 8]