{%hackmd @themes/orangeheart %} ## wk12_1123_CH7函式模組,期末專題 ### 醫放三 B1003210 應雨岑 1. 函式與模組 - 自訂函式 - 數值函式 - 字串函式 - 亂數模組 - 時間模組 2. 專案 ## 今日課程內容 <pre> 1. 期末專題介紹 2. 函式與模組 - 全域、區域變數 - join 函式 3. 專案介紹 - github - 套件的安裝 - 以ping pong game之程式進行介紹 </pre> ## NOTE <pre> join 函式可將串列中元素連接組成一個字串 list1=r.sample(range(1,50),7) #1-50號當中選7個 </pre> ## [ INCLASS PRACTICE ] ```python import random as r list1=r.sample(range(1,50),7) #1-50號當中選7個 print(list1) special=list1.pop() print(f"特別獎號={special}") print(f"中獎號碼={list1}") ``` [43, 34, 27, 29, 36, 14, 28] 特別獎號=28 特別獎號=[43, 34, 27, 29, 36, 14] ```python secret="".join(r.sample("123456789",4)) #1-9數字當中隨機選4個 guess=input("請輸入四個數字") print(secret) a=b=0 for i in range(4): if guess[i]==secret[i]: a=a+1 elif guess[i] in secret: b=b+1 print(f"{a}A{b}B") ``` 請輸入四個數字4567 4823 1A0B ```python import random as r def evaluate(guess): a=b=0 for i in range(4): if guess[i]==secret[i]: a=a+1 elif guess[i] in secret: b=b+1 return a,b secret="".join(r.sample("123456789",4)) #1-9數字當中隨機選4個 while True: guess=input("請輸入四個數字,取消遊戲請直接按enter") if len(guess)==0: print("Bye!!") else: a,b=evaluate(guess) print(f"{a}A{b}B") if a==4 and b==0: print("恭喜答對") break print(secret) ``` 請輸入四個數字,取消遊戲請直接按enter4567 0A2B 請輸入四個數字,取消遊戲請直接按enter4589 0A2B 請輸入四個數字,取消遊戲請直接按enter4512 0A2B 請輸入四個數字,取消遊戲請直接按enter5438 1A1B 請輸入四個數字,取消遊戲請直接按enter5412 0A2B 請輸入四個數字,取消遊戲請直接按enter6424 1A2B 請輸入四個數字,取消遊戲請直接按enter6482 1A2B 請輸入四個數字,取消遊戲請直接按enter7582 0A1B 請輸入四個數字,取消遊戲請直接按enter6942 2A0B 請輸入四個數字,取消遊戲請直接按enter8742 1A1B 請輸入四個數字,取消遊戲請直接按enter8642 1A2B 請輸入四個數字,取消遊戲請直接按enter8641 1A3B 請輸入四個數字,取消遊戲請直接按enter8164 1A3B 請輸入四個數字,取消遊戲請直接按enter1684 0A4B 請輸入四個數字,取消遊戲請直接按enter8461 0A4B 請輸入四個數字,取消遊戲請直接按enter6841 2A2B 請輸入四個數字,取消遊戲請直接按enter6481 1A3B 請輸入四個數字,取消遊戲請直接按enter6148 4A0B 恭喜答對 6148 ```python ! pip install pygame ``` Requirement already satisfied: pygame in c:\users\user\anaconda3\lib\site-packages (2.5.2) ```python #snake game import pygame, sys, time, random difficulty = 25 #設定難度 fps_controller = pygame.time.Clock() direction = 'RIGHT' change_to = direction green = pygame.Color(0, 255, 0) black = pygame.Color(0, 0, 0) #開啟一個新的視窗(先設定視窗大小) frame_size_x = 720 frame_size_y = 480 pygame.display.set_caption('Snake !!') game_window = pygame.display.set_mode((frame_size_x, frame_size_y)) #蛇的大小 snake_pos = [100, 50] snake_body = [[100, 50], [100-10, 50], [100-(2*10), 50]] food_pos = [random.randrange(1, (frame_size_x//10)) * 10, random.randrange(1, (frame_size_y//10)) * 10] food_spawn = True check_errors = pygame.init() # pygame.init() example output -> (6, 0) # second number in tuple gives number of errors if check_errors[1] > 0: print(f'[!] Had {check_errors[1]} errors when initialising game, exiting...') sys.exit(-1) else: print('[+] Game successfully initialised') while True: #對就一直執行 for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: # W -> Up; S -> Down; A -> Left; D -> Right if event.key == pygame.K_UP or event.key == ord('w'): change_to = 'UP' if event.key == pygame.K_DOWN or event.key == ord('s'): change_to = 'DOWN' if event.key == pygame.K_LEFT or event.key == ord('a'): change_to = 'LEFT' if event.key == pygame.K_RIGHT or event.key == ord('d'): change_to = 'RIGHT' # Esc -> Create event to quit the game if event.key == pygame.K_ESCAPE: pygame.event.post(pygame.event.Event(pygame.QUIT)) #蛇不能撞到自己 if change_to == 'UP' and direction != 'DOWN': direction = 'UP' if change_to == 'DOWN' and direction != 'UP': direction = 'DOWN' if change_to == 'LEFT' and direction != 'RIGHT': direction = 'LEFT' if change_to == 'RIGHT' and direction != 'LEFT': direction = 'RIGHT' # if direction == 'UP': snake_pos[1] -= 10 if direction == 'DOWN': snake_pos[1] += 10 if direction == 'LEFT': snake_pos[0] -= 10 if direction == 'RIGHT': snake_pos[0] += 10 snake_body.insert(0, list(snake_pos)) if snake_pos[0] == food_pos[0] and snake_pos[1] == food_pos[1]: score += 1 food_spawn = False else: snake_body.pop() if not food_spawn: food_pos = [random.randrange(1, (frame_size_x//10)) * 10, random.randrange(1, (frame_size_y//10)) * 10] food_spawn = True snake_body.insert(0, list(snake_pos)) snake_body.pop() game_window.fill(black) for pos in snake_body: # Snake body # .draw.rect(play_surface, color, xy-coordinate) # xy-coordinate -> .Rect(x, y, size_x, size_y) pygame.draw.rect(game_window, green, pygame.Rect(pos[0], pos[1], 10, 10)) pygame.display.update() fps_controller.tick(difficulty) ``` pygame 2.5.2 (SDL 2.28.3, Python 3.11.4) Hello from the pygame community. https://www.pygame.org/contribute.html An exception has occurred, use %tb to see the full traceback. SystemExit C:\Users\USER\anaconda3\Lib\site-packages\IPython\core\interactiveshell.py:3513: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D. warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1) ## 全部的note <pre> W1 計算符號之間可以加空白鍵 <br> ** : 幾次方<br> sep="." : 分隔符號為. end="/" : 結束用/結束 在print內寫入%d : 放入參數答案 (最後在答案要加%) %s : 放入的答案為字串 %f : 放入的答案包含全部小數點 %.1f : 包含 1位小數點 %.3f : 包含 3位小數點 寫法如下- print("身高為%d cm,體重為%d kg,BMI為%.1f " % (height,weight,bmi)) print("顯示的文字",參數名字)<br> my_height = input("請輸入身高(cm)") : 可以輸入文字進去對話框 使用者輸入的文字要轉換成"int" ()<br> W2 print("姓名 成績") print("%3s %3d"%(name1,score1)) #按照字元數進行規則排列出一格表格格式 W3 **次方 //整除的數 /除以 %餘數 and 放在兩個運算子中間,判斷True or False,當兩個都為True才會是True or 放在兩個運算子中間,判斷True or False,當兩個都為False才會是False W4 if,else,elif需使用冒號:還有縮排來寫code .upper可以讓程式不用判斷大小寫 W5 串列list用中括弧括起來 for和其他語法一樣,他同樣也是需要用到:還有縮排來寫程式 W6 break會跳出這個迴圈 continue跳出執行這個code 繼續執行下一個i的程式 None 為一個什麼都沒有的數字,但是他可以做加減乘除的運算 W7 串列名稱=[1,2,3,...] #可以放字串、數字等等的 另外也可以宣告空的串列list=[] 多為變數的宣告 list=[["1"],["1,2"],["1,2,3"]] 如果想要顯示第二個串列的第一個內容:print(list[1][0])) # 0表示第一個資料,1表示第二個-意思是程式計算的方式是由0開始數 若想檢索特定的元素可以使用list[起始索引,終止索引,間隔]的方式進行 也可以索引-值,表示從最後一個開始數list[-1] len(list)可以計算元素數量 max(list)可以找到元素內最大值 list.index(...)可以找...在清單中第幾個 .count 可以數...出現幾次 .append 插入一個元素在最後 .insert(3,8)插入8某一個位置(第三個) .pop 移除最後一個元素 W8 divmod(7,3) #答案為(2,1) 表示(商,餘數) 元組內的元素不能修改,但可以轉換成串列 字典是以大括號呈現{} 由小排到大 score.sort() 由大排到小 score.sort(reverse=True) 反轉是錯誤的則不用反轉,由小排到大 score.sort(reverse=False) W9 字典語法 dict_血型個性={"A":"穩重","B":"樂觀","O":"堅強","AB":"自然"} W10 下載code的md檔案--用於期末的hackMd筆記 自訂一個函式 def sayhello(): 呼叫這個sayhello程式 sayhello() 沒有設預設值 def sayhello2(name): #不會出現東西,因為沒有寫預設是什麼 有設定預設值 def sayhello2(name= "my friend"): #沒有特別寫name是什麼,就會使用預設值 如果有一個參數有設預設值另一個沒設,則有設預設值的函數就要放在靠後面 在函式def內設的參數var1=1都是區域變數,如果跳出這個函式後就不存在這個設定,因此如要變成全域函數要用 global var1 \n var1=1 W11 函式模組重點: def,return 只要模組裡面有程式區塊就需要使用return 把time的模組匯成t --> import time as t 匯入time裡面的其他模組,因此在使用時就不需要寫成time.sleep而可直接寫sleep -->from time import sleep,ctime 在python中安裝程式的方法(安裝numpy) --> ! pip install numpy </pre> ## [ afterclass practice ] > 1. 尋找期末專題主題 > - B1003208 江翌榛、 B1003210 應雨岑 >2. 範例 > - 學生分蘋果 \ > - 總和及排序 \ > - 檢查網址格式 \ > - 以字串排版函式列印成績單 \ > - 轉換日期格式 \ >3. 綜合演練 > - 實作3 > - 實作4 * 學生分蘋果 ```python """ 設計程式輸入學生人數及蘋果總數,將蘋果平均分給學生,每個學生分到的蘋果數量必須相同,計算每個學生分到的蘋果數及剩餘的蘋果數。 ex:200個蘋果 15個學生-->每人13個 剩5個 """ people=int(input("請輸入學生人數")) total=int(input("請輸入蘋果總數")) num=total//people less=total%people print(f"每個學生分到{num}個 剩下{less}個") ``` 請輸入學生人數15 請輸入蘋果總數200 每個學生分到13 剩下5 * 總和及排序 ```python """ 設計程式讓爸爸輸入電費,若輸入「-1」表示輸入資料結束,以內建函式顯示最多電費、最少電費、電費總和及將電費由大到小排序 """ list=[] A=int(input("請輸入電費,-1表示輸入結束")) while A!=-1: list.append(A) A=int(input("請輸入電費,-1表示輸入結束")) print(f"最多電費為{max(list)},最少電費為{min(list)},電費總和{sum(list)},電費排序{sorted(list,reverse=True)}") ``` 請輸入電費,-1表示輸入結束1350 請輸入電費,-1表示輸入結束980 請輸入電費,-1表示輸入結束1524 請輸入電費,-1表示輸入結束1073 請輸入電費,-1表示輸入結束-1 最多電費為1524,最少電費為980,電費總和4927,電費排序[1524, 1350, 1073, 980] * 檢查網址格式 ```python """ 設計程式讓使用者輸入網址, 程式會檢查輸入的網址格式是否正確 """ check=input("請輸入網址") if check.startswith("https://") or check.startswith("http://"): print("網址輸入正確") else: print("網址輸入錯誤") ``` 請輸入網址https://www.cgu.edu.tw/ 網址輸入正確 * 以字串排版函式列印成績單 ```python """ 請設計程式幫老師以 rjust 及 ljust 函式整齊列印出班級成績單 """ name=["林大名","陳阿忠","張小英"] number=["1","2","3"] ch=["100","74","82"] math=["87","88","65"] eng=["79","100","8"] print("姓名 座號 國文 數學 英文") print(name[0].ljust(5),number[0].rjust(2),ch[0].rjust(5),math[0].rjust(5),eng[0].rjust(5)) print(name[1].ljust(5),number[1].rjust(2),ch[1].rjust(5),math[1].rjust(5),eng[1].rjust(5)) print(name[2].ljust(5),number[2].rjust(2),ch[2].rjust(5),math[2].rjust(5),eng[2].rjust(5)) #中文字佔2格,,佔1格6 ``` 姓名 座號 國文 數學 英文 林大名 1 100 87 79 陳阿忠 2 74 88 100 張小英 3 82 65 8 * 轉換日期格式 ```python """ 爺爺看不懂以「-」為分隔的日期格式,請設計程式將日期「2017-8-23」轉換為讓爺爺看得懂的「西元 2017 年 8 月 23 日」 """ date=input("請輸入日期") date=date.replace("-","年",1) date=date.replace("-","月",1) print(f"西元{date}日") ``` 請輸入日期2017-8-23 西元2017年8月23日 * 實作3- ```python #以12小制顯示現在時刻 from time import localtime,time #print(localtime()) 測試 #list=localtime() 測試 #print(list) 測試 if list.tm_hour>12: hour=list.tm_hour-12 print("現在時刻:下午",hour,"點",list.tm_min,"分",list.tm_sec,"秒") else: print("現在時刻:下午",list.tm_hour,"點",list.tm_min,"分",list.tm_sec,"秒") ``` 現在時刻:下午 11 點 51 分 47 秒 * 實作4- ```python #媽媽去買菜,希望在找錢時能以最少硬幣數的方法拿到 def buy(money): a=b=c=d=0 a=int(money) if a>=50: b=a%50 a = a/50 if b>10: c=b%10 b=b/10 if c>5: d=c%5 c=c/5 else: d=c else: if b>5: d=b%5 c=b/5 else: b=c else: #<50 if a>10: c=a%10 b=a/10 a=0 if c>5: d=c%5 c=c/5 else: d=c c=0 else: #a<10 if a>5: d=a%5 c=a/5 a=b=0 else: d=a a=b=c=0 return a,b,c,d a,b,c,d=buy(input("請輸入換幣金額")) print("50元有%d個,10元有%d個,5元有%d個,1元有%d個"%(a,b,c,d)) ``` 請輸入換幣金額127 50元有2個,10元有2個,5元有1個,1元有2個 ## [ self practice ] * 大樂透 ```python """ 中獎號碼為 6 個 1 到 49 之間的數字加 1 個特別號:撰寫程式取得大樂透中獎號碼,並由小到大顯示方便對獎。 """ lotte=[] aaa=input("請輸入中獎號碼,結束直接按enter") while aaa!="": lotte.append(aaa) #print(lotte) aaa=input("請輸入中獎號碼,結束直接按enter") bbb=int(input("請輸入特別號碼")) print(f"大樂透中獎號碼為{sorted(lotte)}") print(f"大樂透特別號碼為{bbb}") ``` 請輸入中獎號碼,結束直接按enter12 請輸入中獎號碼,結束直接按enter49 請輸入中獎號碼,結束直接按enter32 請輸入中獎號碼,結束直接按enter10 請輸入中獎號碼,結束直接按enter02 請輸入中獎號碼,結束直接按enter45 請輸入中獎號碼,結束直接按enter 請輸入特別號碼11 大樂透中獎號碼為['02', '10', '12', '32', '45', '49'] 大樂透特別號碼為11
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up