# Python基礎教程 ###### tags: `程式教程` `Python` 可以參考[菜鳥教程](https://www.runoob.com/python/python-tutorial.html) ## Python的基本資料型態 ### 輸出 print() 如果要輸出「嗨嗨你好」 ```python= print('嗨嗨你好') ``` 結果 > 嗨嗨你好 ### 變數型態 #### 整數 : int ```python= x = 100 ``` #### 浮點數 : float ```python= x = 100.0 ``` #### 字串 : str ```python= x = "100" y = '嗨嗨' ``` > '='符號不是等於,而是賦值 #### 多重賦值 同時賦予1 ```python= a = b = c = 1 ``` 各自賦予變數 ```python= a,b,c = 1,2.0,"HaoGe" ``` 互相交換 ```python= x,y = 10,20 print(x,y) x,y = y,x print(x,y) ``` > 10 20 > 20 10 > ### 運算子 <table> <tr> <td>加</td> <td>+</td> </tr> <tr> <td>減</td> <td>-</td> </tr> <tr> <td>乘</td> <td>*</td> </tr> <tr> <td>除</td> <td>/</td> </tr> <tr> <td>取餘數</td> <td>%</td> </tr> <tr> <td>取整數</td> <td>//</td> </tr> <tr> <td>次方</td> <td>**</td> </tr> </table> #### 優先順序 1. 次方 2. 乘、除、取餘數、取整數 3. 加減 ### 指派運算子 <table> <thead> <tr> <td>運算子</td> <td>實例</td> <td>說明</td> </tr> </thead> <tbody> <tr> <td>+=</td> <td>a += b</td> <td>a = a + b</td> </tr> <tr> <td>-=</td> <td>a -= b</td> <td>a = a - b</td> </tr> <tr> <td>*=</td> <td>a *= b</td> <td>a = a * b</td> </tr> <tr> <td>/=</td> <td>a /= b</td> <td>a = a / b</td> </tr> <tr> <td>%=</td> <td>a %= b</td> <td>a = a % b</td> </tr> <tr> <td>//=</td> <td>a //= b</td> <td>a = a // b</td> </tr> <tr> <td>**=</td> <td>a **= b</td> <td>a = a ** b</td> </tr> </tbody> </table> ## 基礎輸入與輸出 ### Python的輔助說明 help() help()函數可以列出某一個Python的指令或函數的使用說明。 ``` python= help(print) ``` 不過其說明都是以英文為基礎,以下我盡量以中文說明 ### 格式化輸出資料使用 print() #### print()的基本語法 其基本語法如下: print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) * **value** 表示想要輸出的資料,可以一次輸出多筆,各資料以逗號隔開。 * **sep** 當輸出多筆資料時,可以插入個比資料的分隔字元,預設是一個空白字元。 * **end** 當資料輸出結束時,預設是一個換行字元,所以下次print()會從下一行開始輸出。如果想下次輸出不換行,可以在此設定為一個空字串或空格等。 * **file** 資料輸出位置,預設是 sys.stdout ,也就是螢幕。可以利用此設定將輸出導至其他檔案或設備。 * **flush** 是否清除緩存,預設為不清除。 ```python= num1 = 111 num2 = 222 num3 = num1+num2 print('這是數值相加:',num3,end='\t') #結尾為一個Tab的距離 str1 = str(num1)+str(num2) print('強制轉換為字串相加',str1,sep = " %%% ") ``` ### 格式化print()輸出 其實python最早也是跟c一樣要用%d、%f等進行輸出 後來在python 2的時候加入了.format()的用法 不過我比較打算介紹python 3的f-string用法 ```python= num1 = 111 num2 = 222 num3 = num1+num2 print(f'這是數值相加:{num3}') ``` 指定輸出位數 ```python= num1 = 2 num2 = 3 num3 = num1/num2 print(f'這是數值相除:{num3:.2f}') ``` ### 資料輸入 input() 此函數與print()功能相反,會讀取使用者輸入的資料。 使用方法如下: value = input(prompt='') 確認輸入資料類型 ```python= name = input('請輸入名字:') score = input('請輸入成績:') print('name資料類型是:',type(name)) print('score資料類型是:',type(score)) ``` 基本資料輸出與運算 ```python= print('歡迎使用成績輸入系統') name = input('請輸入名字:') engh = input('請輸入英文成績:') math = input('請輸入數學成績:') total = int(engh) + int(math) print(f'{name},你的總分是:{total}') ``` 進行小修改,在輸入時就更改型別 ```python= print('歡迎使用成績輸入系統') name = input('請輸入名字:') engh = int(input('請輸入英文成績:')) math = int(input('請輸入數學成績:')) total = engh + math print(f'{name},你的總分是:{total}') ``` ### 處理字串的數學運算 eval() 此函數可以直接傳回字串內的數學表達式的計算結果 使用方法為: result = eval(expression) ```python= num = eval(input('請輸入計算式:')) print(f'計算結果:{num}') ``` 還可以更精簡 ```python= print(f'計算結果:{eval(input())}') #此時input內若有提示字會報錯 ``` 還可以同時賦值 ```python= n1,n2,n3 = eval(input('請輸入3個數字:')) ave = (n1+n2+n3)/3 print(f'平均數為{ave}') ``` > 不過此時輸入得如:30,40,50 在寫練習題時通常的輸入的測試不會是給你使用逗號的,因此以下map()用法請直接記起來 ```python= n1,n2,n3 = map(int,input('請輸入3個數字:').split()) ave = (n1+n2+n3)/3 print(f'平均數為{ave}') ``` > 此時輸入如:30 40 50 ### 關係運算子 | 關係運算子 | 說明 | | ---------- | ---- | | > | 大於 | | >= | 大於或等於| | < | 小於 | | <= | 小於或等於| | == | 等於 | | != | 不等於 | 上述敘述成立則回傳True,不成立則回傳False。 ### 邏輯運算子 and、or、not | and | True | False | |-----|------|-------| |True | True | False | |False| False| False | | or | True | False | |-----|------|-------| |True | True | True | |False| True | False | | not | True | False | |-----|------|-------| | | False| True | ## if...else條件式 ### if敘述 基本語法如下: if(條件判斷):&emsp;&emsp;&emsp;&emsp;#條件判斷外的小括號可有可無 &emsp;&emsp;程式碼區塊 ![](https://i.imgur.com/CIduarV.jpg) python是利用縮排來判斷if的程式碼區塊 編輯時可利用一個Tab或四個空白字元 ### if...else敘述 基本語法如下: if(條件判斷): &emsp;&emsp;程式碼區塊一 else: &emsp;&emsp;程式碼區塊二 ![](https://i.imgur.com/NH2i3Kb.jpg) ### if...elif...else 敘述 基本語法如下: if(條件判斷一): &emsp;&emsp;程式碼區塊一 elif(條件判斷二): &emsp;&emsp;程式碼區塊二 else: &emsp;&emsp;程式碼區塊n ![](https://i.imgur.com/7qcu0U8.jpg) ### 巢狀結構 基本語法如下: if(條件判斷一): &emsp;&emsp;if(條件判斷A): &emsp;&emsp;&emsp;&emsp;程式碼區塊A &emsp;&emsp;else: &emsp;&emsp;&emsp;&emsp;程式碼區塊B else: &emsp;&emsp;程式碼區塊二 ### 題目 1. 有一個圓半徑是20,圓中心在座標(0,0)位置,請輸入任意點座標,這個程式可以判斷此點座標是不是在圓內部。 2. 使用者可以先選擇華氏溫度與攝氏溫度轉換方式,然後輸入一個溫度,可以轉換成另一種溫度。 3. 請輸入3個邊長,如果這3個邊長可以形成三角形則輸出三角形的周長。如果這3個邊長無法形成三角形,則輸出這不是三角形的邊長。 4. 輸入身高體重,輸出BMI與分級結果以及改進意見。 ## 串列(list) ### 串列(list)的基礎特性 其實在其他程式語言中,相類似的功能是陣列(array),如c語言,不過,Python的串列除了可以儲存相同資料,如:*整數*、*浮點數*、*字串*,我們將每一筆資料稱*元素*。一個串列內也可以儲存不同資料型態,如*整數*、*浮點數*和*字串*。甚至一個串列也可以有其他串列、元組(tuple)或是字典(dict)……等當作是它的元素。因此,Python的工作能力,將比其他程式語言更加強大。 ![](https://i.imgur.com/ZiZxJXA.png) 其索引值將從0到n-1,若反過來數則為-1到-n。 創建一個串列,只要把逗號分隔的不同的元素使用中括號括起來即可。如下所示: ```python= list1 = ['physics', 'chemistry', 1997, 2000] list2 = [1, 2, 3, 4, 5 ] list3 = ["a", "b", "c", "d"] ``` 使用索引值來輸出串列中的值,同樣也可以使用中括号進行截取,如下所示: ```python= list1 = ['physics', 'chemistry', 1997, 2000] list2 = [1, 2, 3, 4, 5, 6, 7 ] print(f'list1[0]:{list1[0]}') #輸出list的第0個位置 print(f'list2[1:5]:{list2[1:5]}') #輸出list的從第1個位置到第5個位置前(第4個位置) ``` 結果如下 > list1[0]:physics > list2[1:5]:[2, 3, 4, 5] 如果想要知道這個 list 裡面有幾個元素,可以使用 **len()** 這個函式。 ```python= thriller = ['Thriller', 'Billie Jean', 'Beat It'] print(len(thriller)) ``` 結果如下 > 3 如果超過索引值 ```python= thriller = ['Thriller', 'Billie Jean', 'Beat It'] print(thriller[3]) ``` 就會報錯 > IndexError: list index out of range 指定空字串時可以用以下兩種方式: ```python= lst = list() ``` ```python= lst = [] ``` 恩,基本上都會使用後者,因為比較好打。 #### 與字串類似的特性 |Python表达式|结果|描述| |-----------|---|---| |[1, 2, 3] + [4, 5, 6]| [1, 2, 3, 4, 5, 6]|組合| |['Hi!'] * 4|['Hi!', 'Hi!', 'Hi!', 'Hi!']|重複| |3 in [1, 2, 3]|True|元素是否存在於串列中| |for x in [1, 2, 3]: print x|1 2 3|迭代| #### list 統計函數 在一個串列全是數值時可以使用以下函數 |函數|功用| |---|---| |max()|找出list中最大值| |min()|找出list中最小值| |sum()|計算list的總計值| ```python= score = [60,80,68,54,84,91] print(f'最高得分為:{max(score)}') print(f'最低得分為:{min(score)}') print(f'總計得分為:{sum(score)}') ``` > 最高得分為:91 > 最低得分為:54 > 總計得分為:437 #### 更改串列內容 修改第六個分數 ```python= score = [60,80,68,54,84,91] print(f'原得分為:{score}') score[5] = 100 print(f'新得分為:{score}') ``` > 原得分為:[60, 80, 68, 54, 84, 91] > 新得分為:[60, 80, 68, 54, 84, 100] #### 刪除串列元素 可以使用以下方法刪除串列元素。 del name_list[i] &emsp;&emsp;#刪除索引i的串列元素 下列是刪除串列區間元素。 del name_list[start:end] &emsp;&emsp;#刪除從索引start到索引(end-1)的串列元素 下列是刪除串列區間元素,但在用sep作為每隔多少區間再刪除 del name_list[start:end:step] &emsp;&emsp;#每隔step,刪除從索引start到索引(end-1)的串列元素 ```python= x = [1,2,3] print(x) del x print(x) ``` >[1, 2, 3] >NameError: name 'x' is not defined del後串列便不存在了,於是便會出現沒有定義的報錯。 ### 簡單的物件導向 在物件導向的程式設計觀念裡,所有資料皆算是一個==物件==(Object),例如,==整數==、==浮點數==、==字串==或者是者裡所提的==串列==都是一個物件。我們可以為所建立的物件設計一些方法(method),提供這些物件使用,在這裡所提供的方法表面上像是==函數==,但這函數是放在類別(class)內,我們稱之為==方法==,目前Python有為一些基本物件,提供預設的==方法==,要使用這些==方法==可以在==物件==後先放小數點,在放==方法名稱==,基本語法格式如下: #### 下列為字串常用method: |method|description| |------|-----------| |lower()|將字串轉成小寫字| |upper()|將字串轉成大寫字| |title()|將字串轉成第一個字母大寫,其餘小寫| |rstrip()|刪除字串尾端多餘的空白| |lstrip()|刪除字串開始端多餘的空白| |strip()|刪除字串頭尾兩端多餘的空白| |center()|字串在指定寬度置中對齊| |rjust()|字串在指定寬度靠右對齊| |ljust()|字串在指定寬度靠左對齊| #### 更改字串大小寫lower()/upper()/title() ```python= cars = ['bmw','benz','audi'] print(f'我開的第一部車是{cars[1].title()}') print(f'我現在開的車子是{cars[0].upper()}') ``` >我開的第一部車是Benz >我現在開的車子是BMW 這個有些題目用得到 好,接下來回歸正題 ### 增加與刪除串列元素 #### 在串列末端增加元素 append() 用法: &emsp;&emsp;name_list.append('新增元素') ```python= cars = [] print("目前串列內容 = ",cars) cars.append('Honda') print("目前串列內容 = ",cars) cars.append('Toyota') print("目前串列內容 = ",cars) cars.append('Ford') print("目前串列內容 = ",cars) ``` >目前串列內容 = [] >目前串列內容 = ['Honda'] >目前串列內容 = ['Honda', 'Toyota'] >目前串列內容 = ['Honda', 'Toyota', 'Ford'] #### 插入串列元素 insert() append()僅能在串列末端增加元素,insert()則是可在任意位置插入元素,用法如下: &emsp;&emsp;name_list.insert(索引,新增元素) #索引是插入位置,元素內容是插入內容 ```python= cars = ['Honda','Toyota','Ford'] print("目前串列內容 = ",cars) print("在索引1位置插入Nissan") cars.insert(1,'Nissan') print("新的串列內容 = ",cars) print("在索引0位置插入BMW") cars.insert(0,'BMW') print("最新串列內容 = ",cars) ``` >目前串列內容 = ['Honda', 'Toyota', 'Ford'] >在索引1位置插入Nissan >新的串列內容 = ['Honda', 'Nissan', 'Toyota', 'Ford'] >在索引0位置插入BMW >最新串列內容 = ['BMW', 'Honda', 'Nissan', 'Toyota', 'Ford'] #### 刪除串列元素 pop() 前面雖介紹過del,但其最大缺點便是,刪除了就無法取得相關資訊。使用pop()方法刪除元素最大優點便是刪除後將傳回所刪除的值,使用方法如下: &emsp;&emsp;value = name_list.pop()&emsp;&emsp;#沒有索引是刪除串列末端元素 &emsp;&emsp;value = name_list.pop(i)&emsp;&emsp;#刪除指定索引値i位置的元素 ```python= cars = ['Honda','Toyota','Ford','BMW'] print("目前串列內容 = ",cars) print("使用pop( )刪除串列元素") popped_car = cars.pop( ) # 刪除串列末端值 print("所刪除的串列內容是 : ", popped_car) print("新的串列內容 = ",cars) print("使用pop(1)刪除串列元素") popped_car = cars.pop(1) # 刪除串列索引為1的值 print("所刪除的串列內容是 : ", popped_car) print("新的串列內容 = ",cars) ``` >目前串列內容 = ['Honda', 'Toyota', 'Ford', 'BMW'] >使用pop( )刪除串列元素 >所刪除的串列內容是 : BMW >新的串列內容 = ['Honda', 'Toyota', 'Ford'] >使用pop(1)刪除串列元素 >所刪除的串列內容是 : Toyota >新的串列內容 = ['Honda', 'Ford'] #### 刪除指定的元素 remove() 有時我們想刪除一個元素,但又不確定他在串列中的位置。 &emsp;&emsp;name.remove(想刪除的元素內容) ```python= cars = ['Honda','bmw','Toyota','Ford','bmw'] print("目前串列內容 = ",cars) print("使用remove( )刪除串列元素") expensive = 'bmw' cars.remove(expensive) # 刪除第一次出現的元素bmw print("所刪除的內容是: " + expensive.upper( ) + " 因為太貴了" ) print("新的串列內容",cars) ``` >目前串列內容 = ['Honda', 'bmw', 'Toyota', 'Ford', 'bmw'] >使用remove( )刪除串列元素 >所刪除的內容是: BMW 因為太貴了 >新的串列內容 ['Honda', 'Toyota', 'Ford', 'bmw'] ### 串列的排序 #### 顛倒排序 reverse() 用法: &emsp;&emsp;name_list.reverse()&emsp;&emsp;#顛倒排序name_list串列元素 使用後為永久性更改 ```python= cars = ['Honda','bmw','Toyota','Ford','bmw'] print("目前串列內容 = ",cars) # 直接列印cars[::-1]顛倒排序,不更改串列內容 print("列印使用[::-1]顛倒排序\n", cars[::-1]) # 更改串列內容 print("使用reverse( )顛倒排序串列元素") cars.reverse( ) # 顛倒排序串列 print("新的串列內容 = ",cars) ``` >目前串列內容 = ['Honda', 'bmw', 'Toyota', 'Ford', 'bmw'] >列印使用[::-1]顛倒排序 > ['bmw', 'Ford', 'Toyota', 'bmw', 'Honda'] >使用reverse( )顛倒排序串列元素 >新的串列內容 = ['bmw', 'Ford', 'Toyota', 'bmw', 'Honda'] #### sort()排序 sort()可以讓串列元素由小到大排序,對純數值或純英文字串元素有很好的效果。使用方法如下: &emsp;&emsp;name_list.sort()&emsp;&emsp;#由小到大排序name_list串列 ```python= cars = ['honda','bmw','toyota','ford'] print("目前串列內容 = ",cars) print("使用sort( )由小排到大") cars.sort( ) print("排序串列結果 = ",cars) nums = [5, 3, 9, 2] print("目前串列內容 = ",nums) print("使用sort( )由小排到大") nums.sort( ) print("排序串列結果 = ",nums) ``` >目前串列內容 = ['honda', 'bmw', 'toyota', 'ford'] >使用sort( )由小排到大 >排序串列結果 = ['bmw', 'ford', 'honda', 'toyota'] >目前串列內容 = [5, 3, 9, 2] >使用sort( )由小排到大 >排序串列結果 = [2, 3, 5, 9] 上述內容是由小排到大,sort()方法也允許由大排到小,只要在sort()內增加參數“reverse=True”即可。 ```python= cars = ['honda','bmw','toyota','ford'] print("目前串列內容 = ",cars) print("使用sort( )由大排到小") cars.sort(reverse=True) print("排序串列結果 = ",cars) nums = [5, 3, 9, 2] print("目前串列內容 = ",nums) print("使用sort( )由大排到小") nums.sort(reverse=True) print("排序串列結果 = ",nums) ``` >目前串列內容 = ['honda', 'bmw', 'toyota', 'ford'] >使用sort( )由大排到小 >排序串列結果 = ['toyota', 'honda', 'ford', 'bmw'] >目前串列內容 = [5, 3, 9, 2] >使用sort( )由大排到小 >排序串列結果 = [9, 5, 3, 2] #### sorted()排序 sort()會造成永久性順序更改,若不希望如此可以使用看看sorted(),其方法如下: ```python= cars = ['honda','bmw','toyota','ford'] print("目前串列car內容 = ",cars) print("使用sorted( )由小排到大") cars_sorted = sorted(cars) print("排序串列結果 = ",cars_sorted) print("原先串列car內容 = ",cars) nums = [5, 3, 9, 2] print("目前串列num內容 = ",nums) print("使用sorted( )由小排到大") nums_sorted = sorted(nums) print("排序串列結果 = ",nums_sorted) print("原先串列num內容 = ",nums) ``` >目前串列car內容 = ['honda', 'bmw', 'toyota', 'ford'] >使用sorted( )由小排到大 >排序串列結果 = ['bmw', 'ford', 'honda', 'toyota'] >原先串列car內容 = ['honda', 'bmw', 'toyota', 'ford'] >目前串列num內容 = [5, 3, 9, 2] >使用sorted( )由小排到大 >排序串列結果 = [2, 3, 5, 9] >原先串列num內容 = [5, 3, 9, 2] 如果希望由大排到小,只要在sorted()內增加參數“reverse=True”即可。 ```python= cars = ['honda','bmw','toyota','ford'] print("目前串列car內容 = ",cars) print("使用sorted( )由大排到小") cars_sorted = sorted(cars,reverse=True) print("排序串列結果 = ",cars_sorted) print("原先串列car內容 = ",cars) nums = [5, 3, 9, 2] print("目前串列num內容 = ",nums) print("使用sorted( )由大排到小") nums_sorted = sorted(nums,reverse=True) print("排序串列結果 = ",nums_sorted) print("原先串列num內容 = ",nums) ``` >目前串列car內容 = ['honda', 'bmw', 'toyota', 'ford'] 使用sorted( )由大排到小 排序串列結果 = ['toyota', 'honda', 'ford', 'bmw'] 原先串列car內容 = ['honda', 'bmw', 'toyota', 'ford'] 目前串列num內容 = [5, 3, 9, 2] 使用sorted( )由大排到小 排序串列結果 = [9, 5, 3, 2] 原先串列num內容 = [5, 3, 9, 2] ### 進階串列操作 #### index() 可回傳第一次遇到特定元素的索引值,使用方式如下: &emsp;&emsp;索引值 = 串列名稱.index(搜尋值) 如果*搜尋值不存在*會*出錯*。 ```python= cars = ['toyota', 'nissan', 'honda'] search_str = 'nissan' i = cars.index(search_str) print("所搜尋元素 %s 第一次出現位置索引是 %d" % (search_str, i)) nums = [7, 12, 30, 12, 30, 9, 8] search_val = 30 j = nums.index(search_val) print("所搜尋元素 %s 第一次出現位置索引是 %d" % (search_val, j)) ``` >所搜尋元素 nissan 第一次出現位置索引是 1 所搜尋元素 30 第一次出現位置索引是 2 #### count() 可傳回特定元素出現次數,如果不存在則回傳0,格式如下: &emsp;&emsp;次數 = 串列名稱.count(搜尋值) ```python= cars = ['toyota', 'nissan', 'honda'] search_str = 'nissan' num1 = cars.count(search_str) print("所搜尋元素 %s 出現 %d 次" % (search_str, num1)) nums = [7, 12, 30, 12, 30, 9, 8] search_val = 30 num2 = nums.count(search_val) print("所搜尋元素 %s 出現 %d 次" % (search_val, num2)) ``` >所搜尋元素 nissan 出現 1 次 所搜尋元素 30 出現 2 次 ### 串列內含串列 其基本精神如下: num = [1,2,3,4,5,[6,7]] #### 再談append() 若append()中的元素放的是一個串列,則會將此串列當作另一串列的最後一個元素,此時便會造成串列中有串列的效果,使用方法如下: 串列A.append(串列B) ```python= cars1 = ['toyota', 'nissan', 'honda'] cars2 = ['ford', 'audi'] print("原先cars1串列內容 = ", cars1) print("原先cars2串列內容 = ", cars2) cars1.append(cars2) print("執行append( )後串列cars1內容 = ", cars1) print("執行append( )後串列cars2內容 = ", cars2) ``` >原先cars1串列內容 = ['toyota', 'nissan', 'honda'] 原先cars2串列內容 = ['ford', 'audi'] 執行append( )後串列cars1內容 = ['toyota', 'nissan', 'honda', ['ford', 'audi']] 執行append( )後串列cars2內容 = ['ford', 'audi'] #### extend() 這也是用於兩個串列連接用的方法,不過此方法僅適用於兩串列連接,不能用於一般元素。同時在連接時,extend()會將串列分解成元素,一一插入串列。它的使用方法如下: &emsp;&emsp;串列A.extend(串列B) ```python= cars1 = ['toyota', 'nissan', 'honda'] cars2 = ['ford', 'audi'] print("原先cars1串列內容 = ", cars1) print("原先cars2串列內容 = ", cars2) cars1.extend(cars2) print("執行extend( )後串列cars1內容 = ", cars1) print("執行extend( )後串列cars2內容 = ", cars2) ``` >原先cars1串列內容 = ['toyota', 'nissan', 'honda'] 原先cars2串列內容 = ['ford', 'audi'] 執行extend( )後串列cars1內容 = ['toyota', 'nissan', 'honda', 'ford', 'audi'] 執行extend( )後串列cars2內容 = ['ford', 'audi'] ### 統整 |函式與方法|功能 | |--------|--------| |len(list)|list長度| |max(list)|list最大值| |min(list)|list最小值| |sum(list)|list總計值| |list.append(x)|在list末端增加元素x| |list.insert(x)|插入list元素x| |list.pop(x)|刪除list元素索引值x| |list.remove(x)|刪除list指定的元素x| |list.reverse()|顛倒list排序| |list.sort()|list排序| |sorted(list)|回傳list排序| |list.index(x)|回傳list中x的索引值| |list.count(x)|回傳list中x的數量| |list.extend(x)|在list末端增加串列x的每一個元素| ### 題目 1. 考試成績分數分別是87,99,69,52,78,98,80,92,請列出最高分、最低分、總分、平均。 2. 請在螢幕輸入5個考試成績,然後執行下列工作:(6-5節) (A):列出分數串列。 (B):高分往低分排列。 (C ):低分往高分排列。 (D):列出最高分。 (E):列出總分。 3. 請建立一個晚會宴客名單,有3筆資料”Mary、Josh、Tracy”。請做一個選單,每次執行皆會列出目前邀請名單,同時有選單,如果選擇1,可以增加一位邀請名單。如果選擇2,可以刪除一位邀請名單。以目前所學指令,執行程式一次只能調整一次,如果刪除名單時輸入錯誤,則列出名單輸入錯誤。 ## for迴圈 ### 基本操作 for i in list ```python= players = ['Curry', 'Jordan', 'James', 'Durant', 'Obama'] for player in players: print(player) ``` > Curry Jordan James Durant Obama 若僅一行可不換行 ```python= players = ['Curry', 'Jordan', 'James', 'Durant', 'Obama'] for player in players:print(player) ``` > 同上 ### range() range(start,stop,step) range()函數會產生一個等差級序列,從start開始到stop的前一個,間隔step。 start預設是0,step預設是1。 ```python= for i in range(10): print(i) ``` > 0 1 2 3 4 5 6 7 8 9 ```python= for i in range(1,10): print(i) ``` > 1 2 3 4 5 6 7 8 9 ```python= for i in range(1,11,2): print(i) ``` > 1 3 5 7 9 ### 巢狀for ```python= for i in range(1, 10): for j in range(1, 10): result = i * j print(f"{i}*{j}={result:-3d}", end=" ") print() # 換行輸出 ``` <p>1*1= 1 1*2= 2 1*3= 3 1*4= 4 1*5= 5 1*6= 6 1*7= 7 1*8= 8 1*9= 9 <br> 2*1= 2 2*2= 4 2*3= 6 2*4= 8 2*5= 10 2*6= 12 2*7= 14 2*8= 16 2*9= 18 <br> 3*1= 3 3*2= 6 3*3= 9 3*4= 12 3*5= 15 3*6= 18 3*7= 21 3*8= 24 3*9= 27 <br> 4*1= 4 4*2= 8 4*3= 12 4*4= 16 4*5= 20 4*6= 24 4*7= 28 4*8= 32 4*9= 36 <br> 5*1= 5 5*2= 10 5*3= 15 5*4= 20 5*5= 25 5*6= 30 5*7= 35 5*8= 40 5*9= 45 <br> 6*1= 6 6*2= 12 6*3= 18 6*4= 24 6*5= 30 6*6= 36 6*7= 42 6*8= 48 6*9= 54 <br> 7*1= 7 7*2= 14 7*3= 21 7*4= 28 7*5= 35 7*6= 42 7*7= 49 7*8= 56 7*9= 63 <br> 8*1= 8 8*2= 16 8*3= 24 8*4= 32 8*5= 40 8*6= 48 8*7= 56 8*8= 64 8*9= 72 <br> 9*1= 9 9*2= 18 9*3= 27 9*4= 36 9*5= 45 9*6= 54 9*7= 63 9*8= 72 9*9= 81</p> ### break 跳出迴圈 ```python= print("測試1") for digit in range(1, 11): if digit == 5: break print(digit, end=', ') print( ) print("測試2") for digit in range(0, 11, 2): if digit == 5: break print(digit, end=', ') ``` > 測試1 1, 2, 3, 4, 測試2 0, 2, 4, 6, 8, 10, ### continue 跳過這次迴圈 ```python= scores = [33, 22, 41, 25, 39, 43, 27, 38, 40] games = 0 for score in scores: if score < 30: # 小於30則不往下執行 continue games += 1 # 場次加1 print("有%d場得分超過30分" % games) ``` ### for...else ```python= num = int(input("請輸入大於1的整數做質數測試 = ")) if num == 2: # 2是質數所以直接輸出 print("%d是質數" % num) else: for n in range(2, num): # 用2 .. num-1當除數測試 if num % n == 0: # 如果整除則不是質數 print("%d不是質數" % num) break # 離開迴圈 else: # 否則是質數 print("%d是質數" % num) ``` > 請輸入大於1的整數做質數測試 = 13 13是質數 ## while迴圈 ```python= msg1 = '人機對話專欄,告訴我心事吧,我會重複你告訴我的心事!' msg2 = '輸入 q 可以結束對話' msg = msg1 + '\n' + msg2 + '\n' + '= ' input_msg = '' # 預設為空字串 while input_msg != 'q': input_msg = input(msg) print(input_msg) ``` > 人機對話專欄,告訴我心事吧,我會重複你告訴我的心事! 輸入 q 可以結束對話 = 昊哥牛逼 昊哥牛逼 人機對話專欄,告訴我心事吧,我會重複你告訴我的心事! 輸入 q 可以結束對話 = 昊哥NO.1 昊哥NO.1 人機對話專欄,告訴我心事吧,我會重複你告訴我的心事! 輸入 q 可以結束對話 = q q ### 題目 1. 有一個串列players,這個串列的元素也是串列,包含球員名字和身高資料,[‘James’, 202]、[‘Curry’, 193]、[‘Durant’, 205]、[‘Joradn’, 199]、[‘David’, 211],列出所有身高是200(含)公分以上的球員資料。 2. 請使用for迴圈執行下列工作,請輸入n和m整數值,m值一定大於n值,請列出n加到m的結果。例如:假設輸入n值是1,m值是100,則程式必須列出1加到100的結果是5050 3. 有一個華氏溫度串列fahrenheit內容是[32, 77, 104],這個程式會利用此串列產生攝氏溫度串列celsius。 4. 編寫數字1-5中,2個數字的各種組合 5. 計算數學常數e值,它的全名是Euler’s number,又稱歐拉數,主要是紀念瑞士數學家歐拉,這是一個無限不循環小數,我們可以使用下列級數計算e值。 e=1+1/1!+1/2!+1/3!+⋯+1/i! 這個程式會計算到i=100,同時每隔10,列出一次計算結果。 6. 請輸入2個數,這個程式會求這2個數值的最大公約數(Greatest Common Divisor,簡稱GCD)。所謂的公約數是指可以被2個數字整除的數字,最大公約數是指可以被2個數字整除的最大值。例如:16和40的公約數有,1、2、4、8,其中8就是最大公約數。 ![](https://i.imgur.com/FIKE0d9.png) 7. 有一個串列buyers,此串列內含購買者和消費金額,若是購買金額達到10000元或以上,歸類為infinitebuyers串列。如果購買金額超過或達到1000元,則歸類為VIP買家vipbuyers串列。否則是Gold買家goldbuyers串列。此程式的原始串列資料如下: buyers = [[‘James’, 1030], [‘Curry’, 893], [‘Durant’, 2050], [‘Jordan’, 990], [‘David’, 2110], [‘Kevin’, 15000], [‘Mary’, 10050], [‘Tom’, 8800]] ![](https://i.imgur.com/ndxADOA.png)