隨著程式功能越來越多,所撰寫的程式碼也會越來越龐大,此時要管理複雜的程式並不是很容易的事,此時可以利用函式來控制程式的複雜度。
本章節中原本有將訊息傳送給 Twitter 平台的範例,我將其修正為使用print()顯示訊息來模擬(為了不將時間花費在申請 Twitter 帳號)。
功能需求變更:使用者希望程式可以提供兩種選項,一種是可以直接看到目前咖啡豆的價格(當咖啡豆的庫存太低時,只能緊急下單進貨);另一種則是維持舊有功能,每15分鐘取得一次咖啡豆的價格,直到價錢滿意為止才下單。
程式碼:
import time
price_now = input("Do you want to see the price now ?")
if(price_now == 'Y'):
fileName = "/Coffee.html"
file = open(fileName,'r')
text = file.read()
where = text.find('>$')
start_of_price = where + 2
end_of_price = start_of_price + 4
price = float(text[start_of_price:end_of_price])
print(price)
else:
price = 9999.0
while(price > 6.9):
time.sleep(5)
fileName = "/Coffee.html"
file = open(fileName,'r')
text = file.read()
where = text.find('>$')
start_of_price = where + 2
end_of_price = start_of_price + 4
price = float(text[start_of_price:end_of_price])
print(price)
print('Buy!')
當使用者想要馬上看到價格:
雖然上述的程式可以正確運行,不過可以看到中間有幾行程式碼一模一樣,假設客戶突然又增加了第三種、第四種報價選項,很快的程式碼將變得越來越長且可讀性越來越差,這樣的撰寫方式是不好的,因此請記得一件事:切勿重複你的程式碼!
def FunctionName():
code....
code....
import time
def get_price():
fileName = "/Coffee.html"
file = open(fileName,'r')
text = file.read()
where = text.find('>$')
start_of_price = where + 2
end_of_price = start_of_price + 4
price = float(text[start_of_price:end_of_price])
return price
price_now = input("Do you want to see the price now ?")
if(price_now == 'Y'):
print(get_price())
else:
price = 9999.0
while(price > 6.9):
time.sleep(5)
price = get_price()
print(price)
print('Buy!')
可以看到上述程式碼變得簡潔且可讀性變高,這樣的程式較容易維護。
def send_to_twitter()
msg = "Coffee price is $"
print(msg)
程式碼:
import time
def get_price():
fileName = "/Coffee.html"
file = open(fileName,'r')
text = file.read()
where = text.find('>$')
start_of_price = where + 2
end_of_price = start_of_price + 4
price = float(text[start_of_price:end_of_price])
return price
def send_to_twitter():
msg = "Coffee price is $"
print(msg)
price_now = input("Do you want to see the price now ?")
if(price_now == 'Y'):
send_to_twitter()
else:
price = 9999.0
while(price > 6.9):
time.sleep(5)
price = get_price()
send_to_twitter()
print('Buy!')
執行結果
程式碼:
import time
def get_price():
fileName = "/Coffee.html"
file = open(fileName,'r')
text = file.read()
where = text.find('>$')
start_of_price = where + 2
end_of_price = start_of_price + 4
price = float(text[start_of_price:end_of_price])
return price
def send_to_twitter(price):
msg = "Coffee price is $"+ str(price)
print(msg)
price_now = input("Do you want to see the price now ?")
if(price_now == 'Y'):
send_to_twitter(get_price())
else:
price = 9999.0
while(price > 6.9):
time.sleep(5)
price = get_price()
send_to_twitter(price)
print('Buy!')
執行結果:
功能需求變更:使用者想要為自己的Twitter帳號設定密碼,然後在要送出訊息給Twitter帳號時先檢查一下是否有密碼,有的話才傳訊訊息。
程式碼:
def set_password():
password = "C8H10N402"
set_password()