# 邏輯與程式設計 ## 課程內容:Python * 代課老師:高吉隆 ---- ## 第七章 函數 * 7-1:函數簡介 * 7-2:變數有效範圍 * 7-3:常見Python函數 * 7-4:本章綜合範例 * 利用輾轉相除法求最大公因數 ---- ### 7-2:變數有效範圍 * 亦稱為可視範圍 * 依據變數所在的位置來決定 * 決定哪些敘述句可以合法使用該變數 * 可分為以下二種 * 全域變數:宣告在程式區塊與函數之外 * 可視範圍:所有程式區塊和函數皆可使用 * 生命週期:從設定值至程式結束 * 區域變數:宣告在程式區塊與函數之內 * 可視範圍:僅在該函數內可使用 * 生命週期:從設定值至函數結束 ---- ### 全域變數 vs 區域變數 * 範例1:無法正常計算 num 中所有數乘積 * 每次迴圈都將 product 設為 1 * 結果輸出為最後一項 1 x 1 = 1 ```python= num = [4, 3, 2, 1] # num為全域變數 for j in num: product = 1 # product為區域變數 product *= j # 每次都將 product * j 放入 product print(product) # 列出 product 變數值 ``` ---- ### 全域變數 vs 區域變數 * 範例2:可以正常計算 num 中所有數乘積 * 迴圈之前就將 product 設為 1 * 結果輸出為最後一項 1 x 4 x 3 x 2 x 1 = 24 ```python= num = [4, 3, 2, 1] # num為全域變數 product = 1 # product為全域變數 for j in num: product *= j # 每次都將 product * j 放入 product print(product) # 列出 product 變數值 ``` ---- ### 函數內的區域變數 ```python= def fun(): num = 10 # 函數內的區域變數 for i in range(num): print('*',end='') num = 30 fun() # 依區域變數 num 數值,輸出星星符號 print() for i in range(num): # 依全域變數 num 數值,輸出星星符號 print('*',end='') ``` ---- ### 函數內的全域變數 ```python= def fun(): global num # 函數內使用的全域變數 for i in range(num): print('*',end='') num = 50 # 將全域變數設為 50 num = 30 for i in range(num): # 依全域變數 num 數值,輸出星星符號 print('*',end='') print() fun() # 依區域變數 num 數值,輸出星星符號 print() for i in range(num): # 依全域變數 num 數值,輸出星星符號 print('*',end='') ``` --- ## 常見的 Python 函數 * 數值相關函數 * 字串相關函數 * 序列相關函數 * 參考資料:[連結](https://docs.python.org/3/library/functions.html) ---- ### 數值相關函數 ```python= print('int(8.4)=',int(8.4)) # 8 print('bin(14)=',bin(14)) # 0b1110 print('hex(84)=',hex(84)) # 0x54 print('oct(124)=',oct(124)) # 0o174 print('float(6)=',float(6)) # 6.0 print('abs(-6.4)=',abs(-6.4)) # 6.4 print('divmod(58,5)=',divmod(58,5)) # (11, 3) print('pow(3,4)=',pow(3,4)) # 81 print('round(3.5)=',round(3.5)) # 4 print('chr(68)=',chr(68)) # D print('ord(\'%s\')=%d' %('A',ord('A'))) # 65 print('str(1234)=',str(1234)) # 1234 print('sorted([5,7,1,8,9])=',sorted([5,7,1,8,9])) # [1,5,7,8,9] print('max(4,6,7,12,3)=',max(4,6,7,12,3)) # 12 print('min(4,6,7,12,3)=',min(4,6,7,12,3)) # 3 print('len([5,7,1,8,9])=',len([5,7,1,8,9]))# 5 ``` ---- ### 字串相關函數一 * split(分割字元, 個數上限) ```python= str1 = "apple \nbanana \ngrape \norange" print( str1.split() ) # 沒有指定分割字元,會以空白和換行符號分割 print( str1.split(' ', 2 ) ) # 指定分割字元,並指定分割 2 個 ``` * count(計數字元, 開始位置, 結束位置) ```python= str1="do your best what you can do" s1=str1.count("do",0) # 從索引值0開始計數 do 的出現次數 s2=str1.count("o",0,20) # 從索引值0-20開始計數 d 的出現次數 print("{}\n「do」出現{}次,「o」出現{}次".format(str1,s1,s2)) ``` * strip(首尾去除字元) ```python= str1="Happy new year?" s1=str1.strip("H?") print(s1) ``` ---- ### 字串相關函數二 * replace(搜尋字串, 取代字串) ```python= s= "My favorite sport is baseball." print(s) s1=s.replace("baseball", "basketball") print(s1) # My favorite sport is basketball. ``` * startwith(檢查字串是否開頭為, 開始位置) * endwith(檢查字串是否結尾為, 開始位置) ```python= wd = 'Python is funny and powerful.' print('字串:', wd) print('Python為開頭的字串嗎', wd.startswith('Python')) #回傳True print('funny為開頭的字串嗎', wd.startswith('funny', 0))#回傳False print('funny從指定位置的開頭的字串嗎', wd.startswith('funny', 10)) #回傳True print('powerful.為結尾字串嗎', wd.endswith('powerful.')) #回傳True ``` ---- ### 字串相關函數三 ```python= phrase = 'never put off until tomorrow what you can do today.' print('原字串:', phrase) print('將首字大寫 ', phrase.capitalize()) print('每個單字的首字會大寫', phrase.title()) print('全部轉為小寫字元', phrase.lower()) print('判斷字串首字元是否為大寫', phrase.istitle()) print('是否皆為大寫字元', phrase.isupper()) print('是否皆為小寫字元', phrase.islower()) ``` ---- ### 字串相關函數四 ```python= str1 = '淡泊以明志,寧靜以致遠' print('原字串', str1) print('欄寬20,字串置中', str1.center(20)) print('字串置中,# 填補', str1.center(20, '#')) print('欄寬20,字串靠左', str1.ljust(20, '@')) print('欄寬20,字串靠右', str1.rjust(20, '!')) mobilephone = '931828736' print('字串左側補0:', mobilephone.zfill(10)) str2 = 'Time create hero.,I love my family.' print('以逗點分割字元', str2.partition(',')) str3 = '忠孝\n仁愛\n信義\n和平' print('依\\n分割字串', str3.splitlines(False)) ``` ---- ### 序列相關函數 ```python= str1="I love python." print("原字串內容: ",str1) # I love python print("轉換成串列: ",list(str1)) # ['I',' ','l','o','v','e',' ','p','y','t','h','o','n'] print("轉換成值組: ",tuple(str1)) # ('I',' ','l','o','v','e',' ','p','y','t','h','o','n') print("字串長度: ",len(str1)) # 14 list1=[8,23,54,33,12,98] print("原串列內容: ",list1) # [8,23,54,33,12,98] print("串列中最大值: ",max(list1)) # 98 print("串列中最小值: ",min(list1)) # 8 relist=reversed(list1) # 反轉串列 for i in relist: # 將反轉後的串列內容依序印出 print(i,end=' ') # 98 12 33 54 23 8 print() # 換行 print("串列所有元素總和: ",sum(list1))# 228 print("串列元素由小到大排序: ",sorted(list1)) # [8,12,23,33,54,98] ``` ---- ### 利用輾轉相除法求最大公因數 ```python= def Common_Divisor(): print("請輸入兩個數值") Num1=int(input("數值 1:")) Num2=int(input("數值 2:")) print(Num1,'及',Num2) while Num2 != 0: #利用輾轉相除法計算最大公因數 Temp=Num1 % Num2 Num1 = Num2 Num2 = Temp return Num1 Min=Common_Divisor(); #函數呼叫 print("的最大公因數為:",Min) ``` ---- ### 課後練習 * 網址:https://www.zuvio.com.tw * 帳號:s10812345@ocu.edu.tw * 密碼:123
{"metaMigratedAt":"2023-06-15T01:35:34.792Z","metaMigratedFrom":"Content","title":"邏輯與程式設計","breaks":true,"contributors":"[{\"id\":\"9eed60a5-6546-4dfd-8445-07f81bcfde52\",\"add\":5284,\"del\":180}]"}
    563 views