Quick_start_python_Lessons_6

"function"

Posted by hon20002000 on June 9, 2019

前言

’’’
作者: hon20002000
最後更新: 2019/9/18
‘’’

本教程是為了讓同學們快速體驗機器學習/深度學習而設計的.
裡面只學習最常用的python語法.

想更深入了解python, 網上資源可以看廖雪峰的python教學網站
或是RUNOOB.compython教程 教得十分仔細, 若想深入python的進階用法可以查看他們的內容

教程用法:

閱讀本blog上的基礎語法
完成每篇文章的作業
部分學習所需的檔案在github下載
遇到問題或其他改善建議可在下面留言


正文

函數是為了讓整個程式更簡潔和易讀而編寫的, 也可以將特定功能的一段程序包裝起來重覆使用
例如:

1
2
def print_hello():    #函數的命名一般使用"動詞", 其他變數均使用"名詞"
    print("my name is John, nice to meet you!")

這就是使用函數把print(“my name is John, nice to meet you!”)包裝起來
函數設定後並不會使用, 例如上式便不會print出任何東西, 注意函數須使用def及(:)
裡面的內容須縮進4個空格或1個tab

1
2
3
4
5
6
7
8
9
10
def print_hello():
    print("my name is John, nice to meet you!")

print_hello()
print_hello()
print_hello()
=========== result ==========
my name is John, nice to meet you!
my name is John, nice to meet you!
my name is John, nice to meet you!

這樣便運行了3次函數print_hello(), 函數可以在()內加入變數, 供函數內部使用

1
2
3
4
5
6
7
8
9
10
def print_hello(name):
    print("my name is {}, nice to meet you!".format(name))

print_hello('John')
print_hello('Mary')
print_hello('Susan')
=========== result ==========
my name is John, nice to meet you!
my name is Mary, nice to meet you!
my name is Susan, nice to meet you!

當傳遞給函數的變數多於1個時, 順序是必須的

1
2
3
4
5
6
7
8
def print_hello(name, age):
    print("my name is {}, I am {} years ago!".format(name, age))

print_hello('John', 3)
print_hello(4, 'Mary')
=========== result ==========
my name is John, I am 3 years ago!
my name is 4, I am Mary years ago!

使用此方式可無視順序

1
2
3
4
5
6
def print_hello(name, age):
    print("my name is {}, I am {} years ago!".format(name, age))

print_hello(age=4, name='Mary')
=========== result ==========
my name is Mary, I am 4 years ago!

因此在使用函數時必須清楚函數有多少個變數需要傳遞, 以及變數的名稱是什麼
下面是函數錯誤的使用例子

1
2
3
4
5
6
def print_hello(name, age, school):
    print("my name is {}, I am {} years ago, I study in {}!".format(name, age, school))

print_hello('Mary')
=========== result ==========
TypeError: print_hello() missing 2 required positional arguments: 'age' and 'school'

函數可定義默認值(default值), 不輸入其他值時自動傳入默認值

1
2
3
4
5
6
7
8
def print_hello(name, school='KaoYip'):
    print("my name is {}, I study in {}!".format(name, school))

print_hello('Mary')
print_hello('Mary', 'CDSJ5' )   
=========== result ==========
my name is Mary, I study in KaoYip!
my name is Mary, I study in CDSJ5!

函數的結尾使用return表示輸出結果(返回值)

1
2
3
4
5
6
7
8
def calucale(x):
    y = 3*x + 4
    return y

result = calucale(10)
print("result:", result)   
=========== result ==========
result: 34

return多個返回值

1
2
3
4
5
6
7
8
9
10
11
def calucale(x):
    y = 3*x + 4
    z = -2*x + 1
    return y, z

result_1, result_2 = calucale(10)
print("result_1:", result_1)   
print("result_2:", result_2) 
=========== result ==========
result: 34
result: -19


練習

(a) 利用函數生成字典, 可以應用在生成機器學習的Label之中:
現在有3筆資料
- apple, 3個
- orange, 5個
- waterlemon, 10個
試用函數傳遞參數的方式生成字典fruits = {‘apple’:3, ‘orange’:5, ‘waterlemon’:10}, 例如

1
2
def make_fruit_dict(fruit_dt, fruit, num):
    ...etc

(b) 函數可以傳遞列表, 例如:

1
2
3
4
5
6
7
8
9
10
11
usernames = ['John', 'Mary', 'Susan']
def list_name(users):
    print("user1:", users[0])
    print("user2:", users[1])
    print("user3:", users[2])

list_name(usernames)
=========== result ==========
user1: John
user2: Mary
user3: Susan

usernames列表的的元素數量是可改變的, 我們不能預先在函數內寫出print多少個數據出來
hint: 使用for user in uesrs:

(c) 編寫等差數列的前n項和函數, def sum_ap(a1, d, n):
傳入首項a1, 公差d及項數n, 可以自動求出通項公式an, 並且return an和Sn的值

解答

#(a)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
fruit_dict = {}
def make_fruit_dict(fruit_dt, fruit, num):
    fruit_dt[fruit]=int(num)
    return fruit_dt
 
make_fruit_dict(fruit_dict, 'apple', 3)  
print("fruit_dict:", fruit_dict)  
make_fruit_dict(fruit_dict, 'orange', 5)  
print("fruit_dict:", fruit_dict)  
make_fruit_dict(fruit_dict, 'waterlemon', 10)  
print("fruit_dict:", fruit_dict)  
=========== result ==========  
fruit_dict: {'apple': 3}  
fruit_dict: {'apple': 3, 'orange': 5}  
fruit_dict: {'apple': 3, 'orange': 5, 'waterlemon': 10}  

#(b)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
usernames_1 = ['John', 'Mary', 'Susan']  
usernames_2 = ['John', 'Mary', 'Susan', 'tommy', 'Joan']  
  
def print_user(users):  
    count = 0  
    for user in users:  
        print("user{}:".format(count), user)  
        count += 1  


print_user(usernames_1)  
print('-'*15)   
print_user(usernames_2)  
=========== result ==========    
user0: John  
user1: Mary  
user2: Susan  
---------------  
user0: John  
user1: Mary  
user2: Susan  
user3: tommy  
user4: Joan  

#(c)

1
2
3
4
5
6
7
8
9
10
11
def sum_ap(a1, d, n):    
    Sn = n*a1+n*(n-1)/2  
    an = a1 + (n-1)*d  
    return an, Sn  
  
an, Sn = sum_ap(1,1,10)  
print("an:",an)  
print("Sn:",Sn)  
=========== result ==========    
an: 10  
Sn: 55.0