DAY 28
0

## Day28 Python 基礎 - 函數介紹

### 函數介紹

• 面向對象: 武當派 → 獨門秘笈: 類 → 實現方法: class
• 面向過程: 少林派 → 獨門秘笈: 過程 → 實現方法: def
• 函數式編程: 明教 → 獨門秘笈: 函數 → 實現方法: def

### 函數

``````def test(x):
"""This is test function"""
x += 1
return x
``````
• `def` 是定義函數的關鍵字
• `test` 是函數名稱
• `():` 代表裡面可以放參數，並且準備開始寫子代碼
• `"""This is test function"""` 是註解或是說明功能
• `x += 1` 代碼區或是程序處理邏輯
• `return x` 定義返回值

``````#!/usr/bin/env python3
# -*- coding:utf-8 -*-

# 定義一個函數
def func1():
"""test1"""
print('in the func1')
return 0

# 定義一個過程
def func2():
"""test2"""
print('in the func2')

x = func1()
y = func2()

---------------執行結果---------------

in the func1
in the func2

Process finished with exit code 0
``````

``````#!/usr/bin/env python3
# -*- coding:utf-8 -*-

# 函數
def func1():
"""test1"""
print('in the func1')
return 0

# 過程
def func2():
"""test2"""
print('in the func2')

x = func1()
y = func2()

print('from func1 return is %s' %x)
print('from func2 return is %s' %y)

---------------執行結果---------------

in the func1
in the func2
from func1 return is 0
from func2 return is None

Process finished with exit code 0
``````

`面向過程`就是把你的功能或是邏輯包進去一個 `def 過程`的編程，想用調用時，就可以直接使用 `函數名稱()` 就可以了

• `不是加上return值就是函數編程`

### 為什麼要用函數

``````#!/usr/bin/env python3
# -*- coding:utf-8 -*-

def test1():
print('in the test1')

with open('a.txt', w) as f:
f.write('End action')

def test2():
print('in the test2')

with open('a.txt', w) as f:
f.write('End action')

def test3():
print('in the test3')

with open('a.txt', w) as f:
f.write('End action')
``````

``````#!/usr/bin/env python3
# -*- coding:utf-8 -*-

def logs():
with open('a.txt', 'a+') as f:
f.write('End action\n')

def test1():
print('in the test1')

logs()

def test2():
print('in the test2')

logs()

def test3():
print('in the test3')

logs()

test1()
test2()
test3()

---------------執行結果---------------

in the test1
in the test2
in the test3

Process finished with exit code 0
``````

``````End action
End action
End action
``````

``````#!/usr/bin/env python3
# -*- coding:utf-8 -*-

import  time

def logs():
time_fomate = '%Y-%m-%d %X'
time_current = time.strftime(time_fomate)
with open('a.txt', 'a+') as f:
f.write('%s End action\n' % time_current)

def test1():
print('in the test1')

logs()

def test2():
print('in the test2')

logs()

def test3():
print('in the test3')

logs()

test1()
test2()
test3()

---------------執行結果---------------

in the test1
in the test2
in the test3

Process finished with exit code 0
``````

``````End action
End action
End action
2017-01-14 17:24:38 End action
2017-01-14 17:24:38 End action
2017-01-14 17:24:38 End action
``````

1. 代碼重複使用
2. 保持一致性
3. 可擴展性

Python 學習筆記29

### 2 則留言

0

iT邦好手 1 級 ‧ 2016-12-30 00:44:58

0

iT邦研究生 1 級 ‧ 2016-12-30 01:18:47