## ch07_函式與模組 7.1 自訂函式 1. 自訂函式 2. 參數預設值 3. 變數有效範圍 7.2 數值函式 1. 數值函式整理 2. 指數、商數、餘數及四捨六入 3. 最大值、最小值、總和及排序 7.3 字串函式 1. 字串函式整理 2. 連接及分割字串 3. 檢查起始或結束字串 4. 字串排版相關函式 5. 搜尋即取代字串 7.4 亂數模組 1. import 模組 2. 亂數模組函式整理 3. 產生整數或浮點數的亂數函式 4. 隨機取得字元或串列元素 7.5 時間模組 1. 時間模組函式整理 2. 取得時間訊息函式 3. 執行程式相關時間函式 ```python #以下是一個簡單的猜字遊戲,使用字典作為遊戲中的單詞庫。 #玩家需要猜測英文單詞的意思,並獲得積分。程式會隨機選取一個單詞,玩家需要輸入其意思。 import random # 單詞庫,包含英文單詞和它們的中文意思 word_dict = { "apple": "蘋果", "banana": "香蕉", "cat": "貓", "dog": "狗", "elephant": "大象", "flower": "花朵", "guitar": "吉他", # 添加更多單詞... } score = 0 # 遊戲主迴圈 while True: # 從單詞庫中隨機選擇一個單詞 word, meaning = random.choice(list(word_dict.items())) print(f"請問 '{word}' 的中文意思是?") player_guess = input("請輸入中文意思: ") # 檢查答案是否正確 if player_guess == meaning: print("正確!加10分。\n") score += 10 else: print(f"答錯了,正確答案是 '{meaning}'。\n") # 顯示分數 print(f"你的分數: {score} 分\n") # 問用戶是否繼續遊戲 play_again = input("是否要繼續遊戲?(輸入 'quit' 退出遊戲,其他任意鍵繼續): ") if play_again.lower() == 'quit': break print("遊戲結束,你的最終分數是:", score) ``` 請問 'cat' 的中文意思是? 請輸入中文意思: 貓 正確!加10分。 你的分數: 10 分 是否要繼續遊戲?(輸入 'quit' 退出遊戲,其他任意鍵繼續): quit 遊戲結束,你的最終分數是: 10 ```python print(word_dict.items()) ``` dict_items([('apple', '蘋果'), ('banana', '香蕉'), ('cat', '貓'), ('dog', '狗'), ('elephant', '大象'), ('flower', '花朵'), ('guitar', '吉他')]) ```python type(word_dict.items()) ``` dict_items ```python #因型態是dict_items故要轉型成list random.choice(word_dict.items()) ``` --------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[23], line 2 1 #因型態是dict_items故要轉型成list ----> 2 random.choice(word_dict.items()) File C:\ProgramData\anaconda3\lib\random.py:378, in Random.choice(self, seq) 376 """Choose a random element from a non-empty sequence.""" 377 # raises IndexError if seq is empty --> 378 return seq[self._randbelow(len(seq))] TypeError: 'dict_items' object is not subscriptable ```python random.choice(list(word_dict.items())) ``` ('banana', '香蕉') ### 【inclass practice】 #### {綜合演練} 實作3: 以十二小時(上午、下午)顯示現在時刻。 實作4: 小華媽媽上菜市場買菜,找錢時她希望在1元、5元、10元、50元硬幣中找回最少的硬幣。小華就利用自訂函式幫媽媽寫了一個程式。 #### {範例} 1. 攝氏溫度轉華氏溫度 \<ctof> 2. 學生分蘋果 \<divmod> 3. 總和及排序 \<sorted> 4. 檢查網址格式 \<startswith> 5. 以字串排版函式列印成績單 \<just> 6. 轉換日期格式 \<replace> 7. 擲骰子遊戲 \<randint> 8. 大樂透中獎號碼 \<sample> 9. 列印時間函式所有資訊 \<localtime> 10. 計算執行一百萬次整數運算的時間 \<pcounter> ```python def cT0f(n) : f = 1.8*n+32 return f c = float(input("請輸入攝氏溫度:")) f = cT0f(c) print(f"攝氏{c}度 = 華氏{f}度") ``` 請輸入攝氏溫度:20 攝氏20.0度 = 華氏68.0度 ```python #無預設值 def sayHello(name) : print("hello,歡迎光臨",name) sayHello("Leo") #有預設值 def sayBye(name="my friend") : print(name,"see you again") sayBye() ``` hello,歡迎光臨 Leo my friend see you again ```python def getArea(l,w) : area1 = l*w return area1 area = getArea(150.9,5) print("面積 =",area) ``` 面積 = 754.5 ```python def cicle(radius) : area = radius*radius*3.14 length = radius*2*3.14 return area,length radius = float(input("請輸入半徑:")) A,L = cicle(radius) print(f"半徑{radius} , 圓周{L} , 面積{A}") ``` 請輸入半徑:5 半徑5.0 , 圓周31.400000000000002 , 面積78.5 ```python import time print(time.time()) print(time.localtime()) ``` 1699512735.1322434 time.struct_time(tm_year=2023, tm_mon=11, tm_mday=9, tm_hour=14, tm_min=52, tm_sec=15, tm_wday=3, tm_yday=313, tm_isdst=0) ```python time1 = time.localtime() h = time1.tm_hour if h>12 : now = "下午" else : now = "上午" #print(time1) print(f"現在時間 : {now}{h}點{time1.tm_min}分{time1.tm_sec}秒") ``` 現在時間 : 下午15點2分21秒 #### {補充練習} 1A2B 函式1 : 數字相同+位置相同 函式2 : 數字相同 + 位置不同 ### 【afterclass practice】 綜合演練 選擇題1-10 (需抄題在markdown cell ; 有程式碼的題目要有code cell ) 教學影音: - 新手入門 #07 Function (函式) - 新手入門 #09 Module (模組) 1. 函式的傳回值,下列何者正確? (D) ``` (A)無傳回值 (B) 1 個傳回值 (C) 2 個傳回值 (D)以上皆可 ``` 2. print(max([4,8,3,9,2,6])) 顯示的結果為何? (C) ``` (A)4 (B)6 (C)9 (D)2 ``` 3. print(pow(2,5,7)) 顯示的結果為何? (B) ``` (A)2 (B)4 (C)5 (D)7 ``` 4. print("hospital".replace("s","t")) 顯示的結果為何? (A) ``` (A)hotpital (B)hospisal (C)hospital (D)hotpisal ``` 5. print("hospital".startswith("ho")) 顯示的結果為何? (A) ``` (A)True (B)False (C)hospital (D)ho ``` 6. print("hospital".find("p")) 顯示的結果為何? (C) ``` (A)-1 (B)0 (C)3 (D)4 ``` 7. 下列何者不可能是 print(random.randint(1,10)) 的顯示結果? (A) ``` (A)0 (B)5 (C)8 (D)10 ``` 8. 下列何者不可能是 print(random.randrange(0,15,3)) 的顯示結果? (D) ``` (A)0 (B)3 (C)12 (D)15 ``` 9. 下列哪一個函式可讓程式停止執行一段時間? (B) ``` (A)time (B)sleep (C) perf_counter (D)localtime ``` 10. localtime 傳回的 tm_min 資料範圍為何? (C) ``` (A)1 到 60 (B)0 到 60 (C)0 到 59 (D)1 到 59 ``` ```python import random print("2.",max([4,8,3,9,2,6])) print("3.",pow(2,5,7)) print("4.","hospital".replace("s","t")) print("5.","hospital".startswith("ho")) print("6.","hospital".find("p")) print("7.",random.randint(1,10)) print("8.",random.randrange(0,15,3)) ``` 2. 9 3. 4 4. hotpital 5. True 6. 3 7. 9 8. 6