Python 101

Python 初級

執行方式

執行(1)

執行

            
            python main.py
            
        

執行(2)

執行並導入測資

            
            python main.py < d1.txt
            
        

Output(輸出)

基本輸出

            
            """
            # 內建函式 print()
            # 功能:輸出訊息、變數內容或資料值
            # print(參數:變數或資料值)

            設定函式呼叫步驟:
            1. 設定函式名稱
            2. 放一對圓括 ()
            3. 放參數
            """

            # print(1個參數)
            # 輸出一個字串
            print('Hello, World!')

            # print(0個參數)
            # 單純換行
            print()

            # print(2個以上參數,逗號分隔)
            # 參數輸出時,彼此之間空一白
            print('Hello, World!', 'I am Robot 987.')
            
        

輸出單行字串

可用單引號或雙引號設定字串,必須成對

            
            # 單引號 (字串單引號 vs. 英文單引號)
            print('What\'s going on?')
            # 雙引號
            print("What's going on?")
            
        

輸出不同類別

            
            """
            # 內建函式 type()
            # 功能:回傳變數或資料值的類別
            # type(參數:變數或資料值)
            """

            # 字串 str (string)
            print('123', type('123'))

            # 整數 int (integer)
            print(123, type(123))

            # 浮點數 float
            print(123.0, type(123.0))

            # 布林數 bool (boolean)
            # 例一:硬幣的正反面
            # 例二:電源的開和關
            print(True, type(True))
            print(False, type(False))
            
        

整數格式化

            
            """
            f-string 設定步驟:
            1. 設定小寫 f
            2. 接一對字串單引號 '' 或雙引號 ""
            3. 視需要放「固定字串內容」
            4. 「變數」或「運算式」放在一對花括 {} 中
            """

            a = 7
            b = 2
            x = a + b
            print(f'Sum: {x}')
            
        

浮點數格式化

保留小數位數

            
            """
            f-string 設定步驟:
            1. 設定小寫 f
            2. 接一對字串單引號 '' 或雙引號 ""
            3. 視需要放「固定字串內容」
            4. 「變數」或「運算式」放在一對花括 {} 中
            5. 特定格式要在「變數」或「運算式」後接英文冒號 : 再設定
            6. 保留小數位數,例如 .2f 保留小數後 2 位
            """

            pi = 3.14159
            diameter = 4
            print(f'Perimeter: {pi*diameter:.2f}')
            diameter = 8
            print(f'Perimeter: {pi*diameter:.4f}')
            
        

Input(輸入)

基本輸入

            
            """
            # 內建函式 input()
            # 功能:接收並回傳使用者輸入的資料
            # input(參數:建議設定字串)

            設定函式呼叫步驟:
            1. 設定函式名稱
            2. 放一對圓括 ()
            3. 放參數
            """

            # input(0個參數)
            # 解題使用
            input()

            # input(1個參數)
            # 練習或小專題使用
            input('What is your name? ')
            
        

整數相加

            
            """
            # 內建函式 int()
            # 功能:將「整數字串」或「浮點數」轉為整數
            # int(參數)
            """

            a = int(input('a: '))
            b = int(input('b: '))
            print(a + b)
            
        

浮點數相加

            
            """
            # 內建函式 float()
            # 將「浮點數字串」或「整數」轉為浮點數
            # float(參數)
            """

            a = float(input('a: '))
            b = float(input('b: '))
            print(a + b)
            
        

浮點數取整數

  • 輸入浮點數字串,不可直接用 int() 轉整數
  • 先用 float() 轉浮點數,再用 int() 取整數部分
            
            a = int(float(input('a: ')))
            b = int(float(input('b: ')))
            print(a + b)
            
        

Math(計算)

七種算術運算

            
            # 七種算術運算
            """
            # ex(+).
            # 輸出算術運算結果
            """

            # 加(+)、減(-)、乘(*)、除(/)
            7 + 2
            7 - 2
            7 * 2
            7 / 2
            # 商數(//)、餘數(%)
            # % 其實是模數運算
            7 // 2
            7 % 2
            # 指數 (次方)
            7 ** 2
            
        

運算子優先序

            
            # 運算子優先序
            """
            # ex(+).
            # 圓括 > 指數 > 乘除、商餘 > 加減
            # 先乘除後加減
            # 指乘除餘加減

            # 整數和浮點數計算結果,會得到浮點數
            例如 5 + 1.0 -> 6.0

            Python 的 3 種除法:
            1. /  : 浮點數除法,得到浮點數
            2. // : 整數相除,取商數
            3. %  : 整數相除,取餘數
            """

            a = 7 + 2 - 3 * 2
            print('a:', a)

            b = 8 + 4 / 2 - 5 * 2
            print('b:', b)

            c = 8 * 2 + 7 - 9 / 4 * 3 ** 2
            print('c:', c)

            d = (8 + -4) / 2 - 5 * 2
            print('d:', d)

            e = 27 % 5 * 6 ** 2 - 12 // 6
            print('e:', e)
            
        

整數轉換時機

            
            # 輸入兩個整數字串存到變數 a 和 b
            a = input('a: ')
            b = input('b: ')
            print(a, type(a))
            print(b, type(b))
            print('Result:', a + b)
            print()

            # 因為任何輸入都是字串
            # 所以必須使用 int() 轉成整數
            a = int(a)
            b = int(b)
            print(a, type(a))
            print(b, type(b))
            print('Result:', a + b)
            
        

絕對值

            
            a = int(input('a: '))
            b = int(input('b: '))
            x = a - b
            print(f'Difference = {x}')
            x = abs(x)
            print(f'Absolute value = {x}')
            
        

一行多數(bee1010)

  • 一行字串有多個數據,通常以空白分隔
  • 要將一個長字串切割多個短字串
  • 用 input().split() 將該行字串依空白切割出數據
  • 切割後的數據,全部存到一個串列(list)
  • 可依串列中的數據位置編號(index)取出個別數據
  • index 從 0 開始
            
            alist = input().split()
            print(alist)
            print(alist[0])
            print(alist[1])
            print(alist[2])
            # 將串列中的數據依序分配到不同變數
            a, b, c = alist
            print(a + b + c)
            a = int(a)
            b = int(b)
            c = int(c)
            print(a + b + c)
            
        

和差問題(bee1013)

            
            total = 10
            diff = 4
            large = (total + diff) // 2
            small = (total - diff) // 2
            print(f"Large number: {large}")
            print(f"Small number: {small}")
            
        

平方與平方根(bee1015)

            
            import math

            x = int(input('x: '))
            x = x**2
            print(x)
            x = math.sqrt(x)
            print(x)
            
        

數的次方

            
            # 數的次方
            """
            # ex(+).
            # 使用指數運算 **
            # 輸入 n 和 p
            # 計算 n 的 p 次方

            [輸入與輸出]
            n: 2
            p: 10
            n to the power of p is 1024
            """

            n = input('n: ')
            p = 0
            print(f'n to the power of p = {n}')
            
        

個位與十位

            
            n = int(input('n: '))
            print(f"units digit: {n % 10}")
            print(f" tens digit: {n // 10}")
            
        

位元運算

  • &  (AND)
  • |  (OR)
  • ^  (XOR)
  • << (左移)
  • >> (右移)
            
            a = int(input('a: '))
            b = int(input('b: '))
            print(a & b)
            print(a | b)
            print(a ^ b)
            print(a >> b)
            print(a << b)
            
        

進位制基底與位數範圍

  • 10進位(Dec): 0123456789
  •  2進位(Bin): 01
  •  8進位(Oct): 01234567
  • 16進位(Hex): 0123456789abcdef (a~f 依序表示 10~15)

各種進位值

            
            n = int(input('n: '))
            print(n)
            print(bin(n))
            print(oct(n))
            print(hex(n))
            
        

程式錯誤種類

            
            """
            1. 語法錯誤 Syntax Error  : 不可執行,錯誤類別一律為 SyntaxError
            2. 執行錯誤 Runtime Error : 可以執行,過程可能顯示錯誤訊息
            3. 語意錯誤 Semantic Error: 可以執行,不會顯示錯誤訊息,但結果不符題意

            type(data): 回傳資料的類別
            int('987'): 將數字字串轉成整數 -> integer
            str(12345): 將整數轉成數字字串 -> string
            """

            a = input('A: ))
            b = (input(B: ')
            print(f'A = {a}', type(a))
            print(f'B = {b}', type(b))
            q = a + b
            print(f'The quotient of A over B = {x}')
            
        

Variable(變數)

變數命名法(Snake Case)

兩個以上單字,單字之間以底線連接

            
            """
            # 變數作用:存取資料
            # 存:Set, Save, Store, Conserve
            # 取:Get, Open, Fetch, Retrieve
            """

            your_name = input("What is your name? ")
            your_best_friend = input("Who is your best friend? ")
            print(f"{your_name} & {your_best_friend}")
            
        

兩數對調(交換)

            
            a = int(input('a: '))
            b = int(input('b: '))
            print(f'a: {a}, b: {b}')
            a, b = b, a
            print(f'a: {a}, b: {b}')
            
        

記憶體與變數

整數佔連續空間

            
            """
            記憶體 vs. 變數
            資料盒 vs. 便利貼

            記憶體:如資料盒,是實際存放資料的空間
            變數:如便利貼,可以在不同資料盒間貼來貼去
            """

            a = 1
            print(a, type(a), id(a))
            a = 2
            print(a, type(a), id(a))
            a = 3
            print(a, type(a), id(a))

            print()

            a = '1'
            print(a, type(a), id(a))
            a = '2'
            print(a, type(a), id(a))
            a = '3'
            print(a, type(a), id(a))
            
        

姓名練習一

            
            # 姓名練習一
            """
            # ex(+).
            # 為每一句加上英文句點
            # 分別輸入姓和名,合併姓名存到 user_name
            """

            user_name = input('What is your name? ')
            print('1. Your name is', user_name)
            print('2. Your name is ' + user_name)
            print('3. Your name is %s' % user_name)
            print('4. Your name is {}'.format(user_name))
            print(f'5. Your name is {user_name}')
            
        

姓名練習二

            
            # 姓名練習二
            """
            # ex(+).
            # 保留上題完成的英文句點
            # 分別輸入姓和名,不得合併存到 user_name
            """

            first_name = ''
            last_name = ''
            print('1. Your name is', first_name)
            print('2. Your name is ' + first_name)
            print('3. Your name is %s' % first_name)
            print('4. Your name is {}'.format(first_name))
            print(f'5. Your name is {first_name}')
            
        

語法關鍵字

            
            # 不可設為變數
            """
            False      await      else       import     pass
            None       break      except     in         raise
            True       class      finally    is         return
            and        continue   for        lambda     try
            as         def        from       nonlocal   while
            assert     del        global     not        with
            async      elif       if         or         yield
            """

            global = 'universal'
            
        

簡單異常處理

            
            # 簡單異常處理
            """
            異常錯誤,其實就是執行錯誤

            try:
                可能會發生異常錯誤的程式
                以及相關程式
            except:
                發生異常錯誤時的處理
                可以寫 pass 表示略過
            """
            n = input('n: ')

            try:
                n = int(n)
                print(f'The square of n is {n**2}.')
            except:
                print(f"'{n}' is not an integer.")
            print(type(n))
            
        

Selection(選擇) - 選擇式(分支或選擇結構)

比較運算子

  • ==: 是否相等
  • !=: 是否不相等
  •  >: 大於
  • >=: 大於等於
  •  <: 小於
  • <=: 小於等於
  • 4種 if 區段結構

    • (1) if
    • (2) if-else
    • (3) if-elif... (可以有多個 elif,都必須接條件式)
    • (4) if-elif...else

    if條件式

                
                print("Beebo: Let's hang out.")
                weather = input("How is the weather? ")
                if weather == "sunny":
                    print("(1) Sure. Why not?")
                
            

    if-else條件否則式

                
                print("Beebo: Let's hang out.")
                weather = input("How is the weather? ")
                if weather == "sunny":
                    print("(1) Sure. Why not?")
                else:
                    print("(2) I want to stay home.")
                
            

    三數最大值

                
                alist = input().split()
                a, b, c = alist
                a = int(a)
                b = int(b)
                c = int(c)
                g = a
                if b > g:
                    g = b
                if c > g:
                    g = c
                print(f"The Greatest = {g}")
                
            

    三元運算式

                
                alist = input().split()
                a, b, c = alist
                a = int(a)
                b = int(b)
                c = int(c)
                g = a if a > b else b
                g = g if g > c else c
                print(f"The Greatest = {g}")
                
            

    條件與範圍(成績平均績點)

    移除多餘條件

                
                score = int(input("Score: "))
    
                if score >= 80:
                    print("A, GPA is 4")
                elif score < 80 and score >= 70:
                    print("B, GPA is 3")
                elif score < 70 and score >= 60:
                    print("C, GPA is 2")
                elif score < 60 and score >= 50:
                    print("D, GPA is 1")
                else:
                    print("F, GPA is 0")
                
            

    兩層巢狀選擇(動物連連看)

    先判斷 is_small 再判斷 is_furry

                
                is_furry = True
                is_small = True
                if is_furry:
                    if is_small:
                        print("Cat")
                    else:
                        print("Bear")
                else:
                    if is_small:
                        print("Gecko")
                    else:
                        print("Crocodile")
                
            

    正負奇偶

    先判斷奇偶,再判斷正負

                
                n = int(input('n: '))
                if n == 0:
                    print('zero')
                elif n > 0:
                    if n % 2 == 0:
                        print('Positive Even')
                    else:
                        print('Positive Odd')
                elif n < 0:
                    if n % 2 == 1:
                        print('Negative Odd')
                    else:
                        print('Negative Even')
                
            

    三層巢狀選擇(三個孩子)

    • str.upper(): 字母轉大寫
    • str.lower(): 字母轉小寫
    • 增加第三個孩子的性別判斷
    • 在 Son 及 Daughter 後面,箭頭後方設定英文名字
    • 英文名字不可重複命名
                
                alist = input().split()
                first_born  = alist[0].upper()
                second_born = alist[1].upper()
                third_born  = alist[2].upper()
    
                if first_born == 'M':
                    print('1st child: Son -> Aaron')
                    if second_born == 'M':
                        print('2nd child: Son')
                    else:
                        print('2nd child: Daughter')
                else:
                    print('1st child: Daughter -> Bella')
                    if second_born == 'M':
                        print('2nd child: Son')
                    else:
                        print('2nd child: Daughter')
                
            

    Repetition(重複) - for loop迴圈式(迴圈或重複結構)

    for迴圈結構

    • for 迴圈變數 in 一堆數據:
    • 每次迴圈,從一堆數據中讀取一個,存到迴圈變數
    • 迴圈變數,不一定要在迴圈中使用
    • 數據讀完,就離開迴圈

    輸出整數數列

    • i 是迴圈變數
    • range(stop): 0 ~ stop-1
    • range(5): 產生一堆整數,範圍從 0 到 5-1
    • 迴圈中設定輸出變數 i
                
                for i in range(5):
                    print(i)
                
            

    輸出指定符號

    只有輸出符號,沒有輸出變數 i

                
                for i in range(5):
                    print('*')
                
            

    指定整數範圍

    • range(stop): 0 ~ stop-1
    • range(start, stop): start ~ stop-1
    • range(1, 10): 產生一堆整數,範圍從 1 到 10-1
                
                for i in range(1, 10):
                    print(i)
                
            

    三倍三顆星

    輸出整數 3 ~ 27,i 為 3 的倍數時,輸出 ***,其他值則輸出 *

                
                for i in range(5):
                    if False:
                        print(i, '***')
                    else:
                        print(i, '*')
                
            

    星號三角

    正左直角、倒左直角、正右直角、倒右直角、金字塔形、奇數菱形、三角沙漏

                
                """
    
                # 正左直角
                i *
                1 1 *
                2 2 **
                3 3 ***
                4 4 ****
                5 5 *****
    
                # 倒左直角
                i *
                1 5 *****
                2 4 ****
                3 3 ***
                4 2 **
                5 1 *
    
                # 正右直角
                i . *
                1 4 1     *
                2 3 2    **
                3 2 3   ***
                4 1 4  ****
                5 0 5 *****
    
                # 倒右直角
                i . *
                1 0 5 *****
                2 1 4  ****
                3 2 3   ***
                4 3 2    **
                5 4 1     *
    
                # 金字塔形
                i . *
                1 4 1     *
                2 3 3    ***
                3 2 5   *****
                4 1 7  *******
                5 0 9 *********
    
                # 奇數菱形
                i . *
                1 2 1   *
                2 1 3  ***
                3 0 5 *****
                4 1 3  ***
                5 2 1   *
    
                # 三角沙漏
                i . *
                1 0 5 *****
                2 1 3  ***
                3 2 1   *
                4 1 3  ***
                5 0 5 *****
    
                """
    
                n = int(input('n: '))
                print('# 正左直角')
                for i in range(1, n+1):
                    print('*'*i)
                
            

    偶數相加

                
                n = 10
                total = 0
                for i in range(1, n+1):
                    if i % 2 == 0:
                        total = total + i
                print('Sum of even numbers:', total)
                
            

    等差數列

    • range(start, stop, step): step 為正數或負數,預設為 1
    • start 到 stop 由小到大,表示遞增,step 要設正數
    • start 到 stop 由大到小,表示遞減,step 要設負數
                
                for i in range(1, 10, 2):
                    print(i)
                print()
    
                for i in range(10, 1, -2):
                    print(i)
                print()
                
            

    區分作用命名

                
                # 區分作用命名
                """
                # ex(+).
                # 使兩個相同迴圈輸出同樣結果
                # 不得增加程式行數
                # range() 參數不得直接放整數或算式,但可放變數
                """
    
                i = 5
                for i in range(i):
                    print('i:', i)
                    i = i * 2
                    print('Double of i =', i)
    
                print('-'*20)
    
                for i in range(i):
                    print('i:', i)
                    i = i * 2
                    print('Double of i =', i)
                
            

    for迴圈否則式

                
                for i in range(10):
                    if i % 2 == 0:
                        continue
                    print(i)
                else:
                    print('***')
                
            

    for迴圈否則式 (中斷迴圈)

    break 則 else 相關敘述無效

                
                for i in range(10):
                    if i % 2 == 0:
                        continue
                    if i == 7:
                        break
                    print(i)
                else:
                    print('***')
                
            

    Repetition(重複) - while loop迴圈式(迴圈或重複結構)

    比較運算子

  • ==: 是否相等
  • !=: 是否不相等
  •  >: 大於
  • >=: 大於等於
  •  <: 小於
  • <=: 小於等於
  • while布林變數

                
                isplus = True
                total = 0
                while isplus:
                    total = total + 1
                    print(total)
                    if total == 10:
                        isplus = False
                
            

    while布林值

                
                total = 0
                while True:
                    total += 1
                    print(total)
                    if total == 10:
                        break
                
            

    限定等差數列

    • 維持使用一個條件式
    • 比較雙方維持 total 和 10
    • 調整迴圈內的程式流程
                
                """
                [輸入與輸出]
                step: 2
                2
                4
                6
                8
                10
    
                step: 3
                3
                6
                9
    
                step: 4
                4
                8
                """
    
                total = 0
                while True:
                    total += 1
                    print(total)
                    if total == 10:
                        break
                
            

    while條件式

                
                total = 0
                while False:
                    total += 1
                    print(total)
                    if total == 10:
                        break
                
            

    迴圈式差異

                
                print('# for loop')
                t = 0
                for i in range(10):
                    t += 1
                    print(t)
    
                print('-'*20)
    
                print('# while loop')
                t = 0
                while t < 10:
                    t += 1
                    print(t)
                
            

    迴圈選取圖形

    依選項輸出圖形

                
                while True:
                    print('1.正左直角 2.倒左直角')
                    print('3.正右直角 4.倒右直角')
                    print('5.金字塔形 6.奇數菱形')
                    print('7.三角沙漏 q.離開迴圈')
                    op = input('> ')
                    if op == 'q':
                        break
    
                    n = int(input('n: '))
                    if True:
                        for i in range(1, n+1):
                            print(i)
                    elif True:
                        for i in range(1, n+1):
                            print(i)
                
            

    while迴圈否則式

                
                i = 0
                while i < 10:
                    i += 1
                    if i % 3 == 0:
                        i += 1
                    print(i)
                else:
                    print('***')
                
            

    while迴圈否則式 (中斷迴圈)

    break 則 else 相關敘述無效

                
                i = 0
                while i < 10:
                    i += 1
                    if i % 3 == 0:
                        i += 1
                    elif i % 5 == 0:
                        break
                    print(i)
                else:
                    print('***')
                
            

    進位轉換

    10進位轉 2/8/10/16 進位

                
                strHex = "0123456789abcdef"
                print(strHex)
                n = int(input('N: '))
                while True:
                    break
                print(f"Bin: {bin(n)}")
                print(f"Oct: {oct(n)}")
                print(f"Dec: {n}")
                print(f"Hex: {hex(n)}")
                
            

    梅花座

                
                """
                [輸入與輸出]
                n: 5
                -o-o-
                x-x-x
                -o-o-
                x-x-x
                -o-o-
    
                n: 6
                -o-o-o
                x-x-x-
                -o-o-o
                x-x-x-
                -o-o-o
                x-x-x-
                """
    
                n = int(input('n: '))
                for i in range(n):
                    print('-'*n)
                
            

    質數判斷

    • 輸出 a 到 b 之間的所有質數,一列十數
    • 第一版:第一層使用 for 迴圈
    • 第二版:第一層使用 while 迴圈
                
                a = int(input('a: '))
                b = int(input('b: '))
                for i in range(a, b+1):
                    print(i)
                
            

    錯誤處理

    條件錯誤一

    一次排除一個錯誤,避免增加程式行數

                
                op = input('1.Create 2.Read 3.Update 4.Delete': )
                if op == 1:
                    print(Create)
                elif op == 2:
                    print(Read)
                elif op == 3:
                    print(Update)
                elif op == 4:
                    print(Delete)
                
            

    條件錯誤二

    一次排除一個錯誤,避免增加程式行數

                
                n = input(int('n: '))
                if n % 2 == 0:
                    print('It's an odd.')
                else:
                    print('It's an even.)
                
            

    條件錯誤三

    一次排除一個錯誤,避免增加程式行數

                
                print('L.Left')
                print('R.Right')
                print('U.Up')
                print('D.Down')
                input('> ') = op
    
                if op == 'L'
                    print('Left')
                elif op == 'R'
                    print('Right')
                elif op == 'U'
                    print('Up')
                else op == 'D'
                    print('Down')
                
            

    條件錯誤四

    一次排除一個錯誤,避免增加程式行數

                
                """
                [輸入與輸出]
                How much would you like to deposit? 100
                Enjoy your mug!
                Have a nice day!
    
                How much would you like to deposit? 101
                You get a free toaster!
                Congratulations!
                Have a nice day!
                """
    
                deposit = input('How much would you like to deposit? '))
                freeToaster = False
                if int(deposit) > 100
                    print('You get a free toaster!')
                freeToaster = true
                else:
                    print('Enjoy your mug!')
                if freeToaster:
                print('Congratulations!')
                print('Have a nice day!')
                
            

    迴圈錯誤一

    一次排除一個錯誤,避免增加程式行數

                
                """
                [輸入與輸出]
                n: 5
                *
                **
                ***
                ****
                *****
                """
    
                for i in range(input('n: '):
                print('*'*n+1)
                
            

    迴圈錯誤二

    一次排除一個錯誤,避免增加程式行數

                
                """
                [輸入與輸出]
                n: 10
                2
                4
                6
                8
                10
                """
    
                n = int(input(n: '))
                for i in range(n, 2):
                    if i % 2 = 0:
                    print(i)
                
            

    迴圈錯誤三

    一次排除一個錯誤,避免增加程式行數

                
                """
                [輸入與輸出]
                start: 10
                10
                9
                8
                7
                6
                5
                4
                3
                2
                1
                Time's Up!
                """
    
                countdown = input('start: ')
                While false:
                    print(countdone)
                    countdown -= 1
                    if countdown === 0:
                        print('Time's Up!')
                    break
                
            

    迴圈錯誤四

    一次排除一個錯誤,避免增加程式行數

                
                total = 0
                while true:
                    i = input('Integer (-1 to leave the loop): ')
                    if i == -i:
                        break
                    total += i
                    print(i, total)
                
            

    迴圈錯誤五

    一次排除一個錯誤,避免增加程式行數

                
                """
                [輸入與輸出]
                n: 3
                  t: 0
                    a: 1
                    a: 2
                    a: 3
                    a: 4
                  3
                ----------
                  t: 1
                    a: 2
                    a: 4
                  1
                ----------
                  t: 2
                    a: 3
                    a: 2
                    a: 3
                    a: 2
                    a: 5
                  4
                ----------
                """
    
                n = int(input('n: '))
                for t in range(n):
                    count = 0
                    print('  t:', t)
                    while True:
                        a = input('    a: ')
                        if a < n:
                            break
                        count = 1
                    print(f'  {count}')
                    print('-'*10)
                
            

    迴圈錯誤六

    一次排除一個錯誤,避免增加程式行數

                
                """
                [輸入與輸出]
                n: 3
                ----------
                n: 4
                4
                ----------
                n: 5
                5
                ----------
                n: 6
                6
                66
                ----------
                n: 7
                7
                77
                ----------
                n:
                """
    
                while True:
                    n = input('n: ')
                    if n == '':
                        break
                    m = n / 2
                    for i in range(1, n):
                        print(i*n)
                    print('-'*10)
                
            

    各式錯誤修正

    1. 分母為 0 則輸出 0
    2. 輸入資料存到變數 x
    3. 確保 num1 為整數
    4. 確保 range() 參數為整數
    5. 能轉整數就轉,不能則輸出原值
                
                test_error = input('1, 2, 3, 4 or 5: ')
                if test_error == '1':
                    # ZeroDivisionError
                    incomes = (0, 140, 210, 0, 175, 280)
                    for i in range(1, len(incomes)):
                        print(incomes[i] / incomes[i-1])
                elif test_error == '2':
                    # NameError
                    print(x * 3)
                elif test_error == '3':
                    # TypeError
                    num1 = input('The number: ')
                    num2 = 2
                    print(num1 + num2)
                elif test_error == '4':
                    # TypeError
                    for i in range(input('The stop number: ')):
                        print(i)
                elif test_error == '5':
                    # ValueError
                    data = ('1', 'a', 'A')
                    for cell in data:
                        print(int(cell))
                
            

    一維資料結構

    正整數個數

                
                alist = [3, -2, 4, 5, -6, 0, 7]
                cnt = 0
                # 迴圈讀取整數,讀到正整數則變數 cnt += 1
                for value in alist:
                    if value > 0:
                        cnt += 1
                print(cnt)
                
            

    整數合計

    sum(): 將串列中所有數值合計

                
                alist = [3, 12, 4, 5, 16, 10, 7]
                tot = 0
                # 迴圈讀取整數,並累加到變數 tot
                for value in alist:
                    tot += value
                print(tot)
                print(sum(alist))
                
            

    算術平均數

    len(): 計算串列數據個數

                
                alist = [3, 12, 4, 5, 16, 10, 7]
                avg = sum(alist) / len(alist)
                print(f"Average = {avg:.2f}")
                
            

    串列加法

    兩個串列相加

                
                alist = [1, 2, 3]
                blist = [4, 5, 6]
                clist = alist + blist
                print(clist)
                
            

    串列乘法

    一個串列乘以一個整數 N,表示複製 N 組並合併

                
                alist = [8, 7]
                blist = alist * 5
                print(blist)
    
                alist = [0]
                blist = alist * 10
                print(blist)
                
            

    搜尋指定數值

    • 找到就設定位置索引編號 index
    • -1 表示找不到
                
                alist = [3, 12, 4, 5, 16, 10, 7]
    
                n = int(input('n: '))
                the_index = -1
                for i in range(len(alist)):
                    print(f'{i} -> {alist[i]}')
                    if alist[i] == n:
                        the_index = i
                        break
                if the_index == -1:
                    print('Not found.')
                else:
                    print(f'The index of {n} is {the_index}.')
                
            

    索引函式用法

    • 先用 in 操作確認要搜尋的數值是否在串列中
    • 再用 list.index(value) 找到位置索引編號
                
                alist = [3, 12, 4, 5, 16, 10, 7]
    
                n = int(input('n: '))
                the_index = -1
                if n in alist:
                    the_index = alist.index(n)
                if the_index == -1:
                    print('Not found.')
                else:
                    print(f'The index of {n} is {the_index}.')
                
            

    串列新增數據

                
                alist = list(range(1, 6))
                print(alist)
    
                n = len(alist)
                for i in range(n):
                    alist.append(alist[i]*2)
                print(alist)
                
            

    串列新增亂數

    random.randrange(): 參數設定規則與 range() 相同

                
                import random
    
                alist = []
                for i in range(5):
                    rnum = random.randrange(1, 51)
                    alist.append(rnum)
                print(alist)
                
            

    串列排序

    sorted(): 可對字串或串列排序,排序結果存到串列

                
                import random
    
                alist = []
                for i in range(5):
                    rnum = random.randrange(1,51)
                    alist.append(rnum)
                print(alist)
                # 升冪排序
                alist = sorted(alist)
                print(alist)
                # 降冪排序
                alist = sorted(alist, reverse=True)
                print(alist)
                
            

    基本排序法

    氣泡排序、選擇排序、插入排序

                
                import random
    
                # 設定亂數種子
                random.seed(5)
                alist = []
                for i in range(5):
                    rnum = random.randrange(1,51)
                    alist.append(rnum)
                print(alist)
                
            

    基礎解題操作

    最外層使用 while 迴圈

      可處理
    • 一個測資檔,一組測資
    • 一個測資檔,多組測資
    • 主要程式放在 try 區段
    • 讀取測資直到 EOF 就離開迴圈
    • EOF: End Of File (檔案結束)

    哈囉!同學

                
                """
                [輸入]
                Jane
                John
    
                [輸出]
                hello, Jane
                hello, John
                """
    
                while True:
                    try:
                        # 讀取一行字串
                        s = input()
                        # 依題意輸出訊息
                        print('hello, ' + s)
                    except EOFError:
                        break
                
            

    奇數偶數

                
                """
                [輸入]
                8
                21
                7
                12
    
                [輸出]
                even
                odd
                odd
                even
                """
    
                while True:
                    try:
                        # 讀取一行字串,將字串轉成整數
                        n = int(input())
                        # 偶數除以 2 的餘數為 0
                        # 奇數除以 2 的餘數為 1
                        if n % 2 == 0:
                            print('even')
                        elif n % 2 == 1:
                            print('odd')
                    except EOFError:
                        break
                
            

    一行多數轉整數

      必記 list(map(int, input().split()))
    • 字串 list -> 整數 map -> 整數 list
    • input().split(): 將一行字串依空白切割成小字串 -> 字串 list
    • map(轉換函式名稱, 數據串列)
    • map(int, input().split()): map(轉成整數, 字串串列) -> 整數 map
    • list(map_object): 將 map 物件轉成整數串列 -> 整數 list

    相差絕對值

                
                """
                [輸入]
                10 20
                30 12
    
                [輸出]
                10
                18
                """
    
                while True:
                    try:
                        # a, b = list_object: 整數串列中有 2 個整數,用 2 個變數分配儲存
                        a, b = list(map(int, input().split()))
                        # 使用絕對值函式 abc()
                        print(abs(a-b))
                    except EOFError:
                        break
                
            

    N數相加

                
                """
                [輸入]
                5 9 1 6 8
                9 8 7
                1 7 3 8
    
                [輸出]
                29
                24
                19
                """
    
                while True:
                    try:
                        alist = list(map(int, input().split()))
                        # 用合計函式 sum() 將整數 list 中的全部整數加總
                        print(sum(alist))
                    except EOFError:
                        break
                
            

    最大減最小

                
                """
                [輸入]
                10 20 35
                30 12 24 48
    
                [輸出]
                25
                36
                """
    
                while True:
                    try:
                        alist = list(map(int, input().split()))
                        # 用最大值函式 max() 取出整數 list 中的最大數
                        max_value = max(alist)
                        # 用最小值函式 min() 取出整數 list 中的最小數
                        min_value = min(alist)
                        result = max_value - min_value
                        print(result)
                    except EOFError:
                        break
                
            

    不定N數相加

                
                """
                [輸入]
                5
                9
                1
                6
                8
                -1
                9
                8
                7
                -1
    
                [輸出]
                29
                24
                """
    
                while True:
                    try:
                        # 迴圈前設定 total 變數 為 0
                        # 準備在迴圈內將整數累加到 total
                        total = 0
                        while True:
                            n = int(input())
                            if n == -1:
                                # 離開迴圈前輸出 total
                                print(total)
                                # 離開本層迴圈
                                break
                            # 將整數 n 加到 total
                            total += n
                    except EOFError:
                        break
                
            

    N行平均

                
                """
                [輸入]
                4
                5 9 1 6 8
                9 8 7
                1 7 3 8
                1 3 1 4 9 8 7
    
                [輸出]
                5.80
                8.00
                4.75
                4.71
                """
    
                while True:
                    try:
                        n = int(input())
                        for i in range(n):
                            alist = list(map(int, input().split()))
                            # 用計算函式 len() 計算 list 的數據個數
                            average = sum(alist) / len(alist)
                            print(f'{average:.2f}')
                    except EOFError:
                        break
                
            

    上下兩數相加

                
                """
                [輸入]
                7
                5 9 1 6 8 8 8
                1 3 1 4 9 8 7
    
                [輸出]
                6 12 2 10 17 16 15
                """
    
                while True:
                    try:
                        n = int(input())
                        # alist: 整數 list
                        alist = list(map(int, input().split()))
                        # blist: 整數 list
                        blist = list(map(int, input().split()))
                        # clist: 空的 list
                        clist = []
                        for i in range(n):
                            # 用 indexing 操作取出兩個整數 list 的第 i 個整數後相加
                            # 用 list.append() 方法將上下兩數合計值新增到 clist
                            clist.append(alist[i] + blist[i])
                        # 展開輸出 clist 中的整數
                        print(*clist)
                    except EOFError:
                        break
                
            

    排序取前三大

                
                """
                [輸入]
                6 12 2 10 17 16 15
    
                [輸出]
                2 6 10 12 15 16 17
                17 16 15 12 10 6 2
                17 16 15
                """
    
                while True:
                    try:
                        alist = list(map(int, input().split()))
                        # 由小到大排序
                        alist.sort()
                        print(*alist)
                        # 由大到小排序
                        alist.sort(reverse=True)
                        print(*alist)
                        # 用 slicing 操作取出前三大整數
                        print(*alist[:3])
                    except EOFError:
                        break
                
            

    合計營收

                
                """
                [輸入]
                4
                A 10 1 1.0
                B 20 8 0.8
                C 30 5 0.9
                A 10 12 0.8
                3
                E 12 12 0.8
                F 28 4 0.9
                E 36 2 0.95
    
                [輸出]
                369
                284
                """
    
                while True:
                    try:
                        n = int(input())
                        total = 0
                        for i in range(n):
                            # 一行字串含字母、整數、浮點數字串,不可以使用 map()
                            alist = input().split()
                            # 將第 2 個和第 3 個字串轉成整數
                            price = int(alist[1])
                            quantity = int(alist[2])
                            # 將第 4 個字串轉成浮點數
                            discount = float(alist[3])
                            total += price * quantity * discount
                        print(int(total))
                    except EOFError:
                        break
                
            

    字母使用個數

                
                # 字母使用個數
                """
                [檔案]
                The story of a team of female African-American mathematicians
                who served a vital role in NASA during the early years of
                the U.S. space program.
    
                [輸出]
                A 18
                C 4
                D 2
                E 14
                F 5
                G 2
                H 5
                I 7
                L 4
                M 6
                N 6
                O 7
                P 2
                R 10
                S 7
                T 8
                U 2
                V 2
                W 1
                Y 3
                B J K Q X Z
                """
    
                alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
                # adict: 空的 dict
                # adict[key] = value -> adict[字母] = 個數
                adict = dict()
    
                while True:
                    try:
                        # 讀取一行字串並將字母全部轉成英文大寫
                        line = input().upper()
                        for char in line:
                            # 判斷 char 是否為字母
                            if char.isalpha():
                                # 累加 char 字母個數
                                adict[char] = adict.get(char, 0) + 1
                    except EOFError:
                        break
    
                # 將字母排序後存到字串 list
                sorted_letters = sorted(adict.keys())
    
                # 逐一讀取 sorted_letters 串列的字母
                for letter in sorted_letters:
                    # 對 adict 詞典依鍵取值 -> 字母個數
                    print(letter, adict[letter])
    
                # 將 alphabet 字串轉成集合
                # 將 sorted_letters 串列轉成集合
                # 用差集運算得知未使用的字母後存到 aset 集合
                aset = set(alphabet) - set(sorted_letters)
    
                # 將未使用的字母排序後存到 unused_letters 串列
                unused_letters = sorted(aset)
                print(*unused_letters)
                
            

    方陣元素遞增

                
                """
                [輸入]
                3
                0 1 0
                2 3 2
                0 1 0
                3
                1 2 1
                3 1 3
                1 2 1
                5
                1 2 3 2 1
                4 3 2 1 0
                2 1 0 1 2
                0 1 2 3 4
                2 1 3 1 2
    
                [輸出]
                0 1 0
                2 3 2
                0 1 0
                9
                3 4 3
                5 3 5
                3 4 3
                33
                6 7 8 7 6
                9 8 7 6 5
                7 6 5 6 7
                5 6 7 8 9
                7 6 8 6 7
                169
                """
    
                while True:
                    try:
                        n = int(input())
                        # table: 預備放二維數據
                        table = []
                        for ri in range(n):
                            row = list(map(int, input().split()))
                            # 將 row 整數串列新增到 table 串列
                            # table 串列中有 row 串列,使 table 變成二維串列
                            table.append(row)
    
                        # 計算中間格的 index 位置編號
                        # ri: row index (列座標)
                        # ci: col index (欄座標)
                        center_ri = n // 2
                        center_ci = n // 2
    
                        while True:
                            # 判斷中間格整數是否等於 n
                            if table[center_ri][center_ci] == n:
                                # True 則輸出 table
                                total = 0
                                for ri in range(n):
                                    print(*table[ri])
                                    for ci in range(n):
                                        total += table[ri][ci]
                                print(total)
                                break
                            else:
                                # False 則將 table 中每個整數再加 1
                                for ri in range(n):
                                    for ci in range(n):
                                        table[ri][ci] += 1
                    except EOFError:
                        break