robylin
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 主題 * function * recurrence * class # 責編的話 * 內容先以補充為主,之後再濃縮 * 主要是介紹,可參考reference [TOC] # function - [x] 學習目標 * 函式的基礎概念 * 提升程式的可讀性與可維護性。 - [x] 知識點 1.什麼是函式?為什麼要使用函式? * 函式與程式模組化的關係。 * 使用 def 關鍵字定義函式。 * 函式名稱與命名規範,程式碼縮排規則(`空4格`),參數 ```python= def 函式名稱(參數) 程式碼 ``` 3.位置參數與關鍵字參數的區別。 * 預設參數值 (default arguments)。 ```python= # 預設參數值 def greet(name, message="Hello"): return f"{message}, {name}!" # 呼叫函式 print(greet("Alice")) print(greet("Bob", message="Hi")) ``` * 可變參數 (`*args`, `**kwargs`)。(可用表格提取關鍵字比較) * `*args`:這個語法允許將不確定數量的**無定義字參數**傳遞給函式。`*args` 在函式內部被視為一個包含所有非關鍵字參數的元組。 * `**kwargs`:這個語法允許將不確定數量的**定義參數**傳遞給函式。`**kwargs` 在函式內部被視為一個包含所有關鍵字參數的字典。 ```python= # 使用 *args 處理任意數量的參數 def sum_all(*args): return sum(args) print(sum_all(1, 2, 3, 4)) # 10 # 使用 **kwargs 接收關鍵字變數 def print_info(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") print_info(name="Alice", age=25, country="USA") ``` * 這種方式對於定義不確定數量的參數很有用,特別是在寫通用的函式時,或者當你不確定有多少參數需要傳遞給函式時。需要注意的是,`*args` 和 `**kwargs` 是約定俗成的命名方式,你可以使用其他名稱,但一般來說,使用這兩個名稱可以讓你的程式碼更易讀。 (撰寫具參數化的通用函式。) 4. 使用 return 關鍵字返回值。 ```python def f(x): return x**2 - math.cos(x) ``` 5. 區分局部變數 (local variables) 與全域變數 (global variables)。(表格部分寫得有點細選擇重要部分說明即可) * 變數的作用域與生命週期 * 全域變數 (Global Variables) vs 區域變數 (Local Variables) ![image](https://hackmd.io/_uploads/SytbSlUQJl.png) | 特性 | 全域變數 (Global Variables) | 區域變數 (Local Variables) | |------------------|--------------------------------------------------|---------------------------------------------| | **定義範圍** | 程式全域內皆可存取 | 只在函式或區塊內有效 | | **存取範圍** | 可被任何函式存取與修改 | 只能在定義的函式或區塊內存取 | | **作用時間** | 自程式執行開始至結束 | 隨函式或區塊執行結束而釋放 | | **記憶體使用**| 常駐於記憶體,可能耗費較多資源| 僅在函式或區塊執行時分配記憶體 | | **影響範圍** | 可能導致整個程式的不預期行為(如意外覆蓋變數)| 影響範圍較小,易於維護 | | **適用場景** | 常用於需共享資料的全域設定(如配置、常數等)| 適用於僅需暫時存取或操作資料的情境 | | **可讀性** | 可能導致程式較難理解(若過多使用) | 增加可讀性,函式封裝使變數更易追蹤 | | **修改風險** | 高:任何函式都可能意外更改| 低:僅限定義的函式或區塊能修改 | 6.如何撰寫清晰、簡單且高效的函式。 (選用) * 函式的測試與除錯技巧。 * 設置中斷點(break point) * 將變數print出 7.使用 lambda 關鍵字定義匿名函式。 ```python= # 使用 lambda 簡化函式 square = lambda x: x ** 2 print(square(4)) # 16 # 與高階函式結合 numbers = [1, 2, 3, 4] squared_numbers = list(map(lambda x: x ** 2, numbers)) print(squared_numbers) # [1, 4, 9, 16] ``` * 適合使用匿名函式的場景。 * 快速創建一個小型、臨時性的函數,並且不想為其命名以節省整個記憶體空間時 8.學習 Python 提供的常用內建函式,例如 `len()`、`max()` 等。 ```python= my_string = "Hello World!" length = len(my_string) print(length) ``` ![image](https://hackmd.io/_uploads/H1qHGZUQ1e.png) ```python= print(max(4, 6)) print(max(11, 7)) print(max(16.6, 18.1)) ``` ![image](https://hackmd.io/_uploads/SydhZZImke.png) 9.函式作為參數傳遞給其他函式。 * 使用進階函式,例如 map()、filter() 和 reduce()。 ```python= # 函式作為參數傳遞 def apply_operation(a, b, operation): return operation(a, b) # 定義一些操作函式 def multiply(x, y): return x * y def subtract(x, y): return x - y # 呼叫函式 print(apply_operation(10, 5, multiply)) # 50 print(apply_operation(10, 5, subtract)) # 5 ``` # recursion - [x] 學習目標 * 熟悉 Python 中遞迴 (recursion) 的概念與應用,能夠有效地設計並實現遞迴演算法來解決分治與重複結構的問題 - [ ] 知識點 1.遞迴的基本概念 * 什麼是遞迴? * 一種通過重複將問題分解為同類的子問題而解決問題的方法 * 遞迴與迴圈的異同。 * 迴圈是大範圍同時執行(跑),而事先就給了範圍。但遞迴把要做的方法分成一個個小部分,而沒給範圍 * 遞迴的適用場景,例如分治法divide and conquer(分而治之,問題分解成小問題以便解決) 和數學歸納結構(一種數學證明方法,通常被用於證明某個給定命題在整個或者局部自然數範圍內成立。)的問題。 2.遞迴函式的結構 * 基底情況 (base case):有初始項,避免無限遞迴。 * 遞迴情況 (recursive case):問題的分解與遞迴的邏輯。 * 遞迴的特性:記憶體消耗與堆疊 (call stack)。 * 最大遞迴深度與 Python 的 RecursionError。 * 遞迴的典型應用: * (1)數學問題:如階乘 (factorial)、斐波那契數列 (Fibonacci sequence)。 * 階乘函數(factorial) ```python= def factorial(n): if n == 0 or n == 1:#基底情況 0! = 1 , 1! = 1 return 1 else: return n * factorial(n-1)#不是0 or 1呼叫函式自身 i = 5 print(i,"!=", factorial(i)#印出 0! j = 0 print(j,"!=", factorial(j))#印出 1! ``` ![image](https://hackmd.io/_uploads/SkghRfW8mkx.png) * 斐波那契數列 (Fibonacci sequence) ```python= def fib(n): if n > 1: return fib(n-1) + fib(n-2) #呼叫函式本身 return n # 基底條件0、1回傳本身 for i in range(20): print(fib(i), end = ',') #印到第20項 ``` ![image](https://hackmd.io/_uploads/rkHjmZUXyx.png) * (2)資料結構問題:如樹的遍歷 (tree traversal)、最大深度計算等。 字串與陣列操作:如反轉字串、搜尋與分割問題。 * (3)分治法應用:如快速排序 (quick sort)、合併排序 (merge sort)。 * quick sort ![image](https://hackmd.io/_uploads/HkwhJ-IQ1x.png) * merge sort ![image](https://hackmd.io/_uploads/H1n6k-I7kg.png) 3.何時應將遞迴轉為迴圈以提升效能與穩定性。 * 使用堆疊模擬遞迴過程。 ![image](https://hackmd.io/_uploads/H1feGuHQyg.png) # class - [x] 學習目標 * 掌握 Python 中class (類別) 的概念與應用,理解其核心原則之一(繼承),並將其應用於解決實際問題。 - [ ] 知識點 1.類別與物件的基本概念 * 什麼是類別 (class) 和物件 (object)? * 類別算是一個藍圖、一個範本、一個可參考的文件,他沒有實體(Instance) 的概念,屬靜態的。 物件是一個看的到、摸的到的實體,屬於動態的,狀態會隨時改變,但架構與行為不會改變 | **Aspect** | **Class** | **Object** | |----------------------|---------------------------------------------------------------------------|----------------------------------------------------------------------| | **定義 (Definition)** | 類別是一個藍圖或模板,用來定義物件的屬性和行為。 | 物件是類別的實例,表示特定的資料和行為。 | | **概念 (Concept)** | 類別是抽象的,不消耗記憶體。 | 物件是具體的,消耗記憶體來儲存資料。 | | **用途 (Purpose)** | 提供一個統一的結構,讓程式具備可重用性與可擴展性。 | 實現類別定義的行為,處理具體資料和任務。 | | **關係 (Relationship)** | 是物件的模板 (Blueprint)。 | 是類別的實例 (Instance)。 | | **屬性與模式 (Attributes & Methods)** | 包含定義屬性與方法的程式碼,但不直接執行或儲存特定值。 | 擁有實際的屬性值與行為,可透過方法互動。 | | **範例 (Example)** | `class Car:` <br>` def __init__(self, brand):` <br>` self.brand = brand` | `my_car = Car("Toyota")` <br> `print(my_car.brand)` (輸出 `Toyota`) | | **存在性 (Existence)**| 定義時存在於程式碼中。 | 必須通過類別實例化,才能存在於記憶體中並被操作。 | | * **為什麼使用class來組織程式碼** * 清晰地表達資料和行為之間的關係。 * 減少程式碼重複,提升效率。 * 提高程式碼的可讀性、可維護性和可擴展性。 * 模擬現實中的概念,使程式設計更貼近現實。 2.定義與實例化類別 * 使用 `class` 關鍵字定義類別。 * 建立類別實例 (物件)。 * `__init__` 方法:初始化屬性,讓物件有自己的資料。 ```python class Dog: def __init__(self, name, age): self.name = name self.age = age def bark(self): print(self.name + "正在叫!") def describe(self): print(self.name + "的年齡是" + str(self.age) + "歲。") # 創建 Dog 類別的物件 dog1 = Dog("旺財", 3) dog2 = Dog("小黑", 2) # 使用物件的方法 dog1.bark() # 旺財正在叫! dog2.describe() # 小黑 的年齡是 2 歲。 ``` ![image](https://hackmd.io/_uploads/HypXb8oQyx.png) 3.類別的屬性與方法 * 定義和使用實例屬性(如物件的特性)。 * 定義和呼叫實例方法(如物件的行為)。 * self 的作用和用法(self代表物件自身)。 ```python class Calculator: def __init__(self): pass # 此處無需初始化屬性 def add(self, a, b): return a + b def subtract(self, a, b): return a - b # 使用類別創建物件並呼叫方法 calc = Calculator() print(calc.add(10, 5)) # 15 print(calc.subtract(10, 5)) # 5 ``` 4. class 權限 * 類別成員 x 可以宣告為具有下列其中一個權限: * public : x 可在任何地方使用,不受專用或受保護所定義的存取限制。 * private : x 只能由類別 A 的成員使用。 * protected : x 只能由類別 A 的成員,以及衍生自類別 A 的類別成員使用 5. 繼承的基本語法與使用方法。 * 子類別 (subclass) 與父類別 (superclass) 的關係。 `super()` 函式的使用。 | **項目** | **父類別 (Superclass)** | **子類別 (Subclass)** | |--------------------|---------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------| | **定義** | 提供基礎功能和屬性,是其他類別繼承的來源。| 繼承父類別的功能,可以新增或覆寫部分功能。 | | **功能重點** | 定義通用的屬性與方法,適用於多個相關類別。 | 擴展或自訂父類別的功能,實現更具體的需求。 | | **繼承關係** | 不需要繼承其他類別,但可以被其他類別繼承。 | 繼承自父類別,並獲得父類別的所有屬性與方法(除私有屬性外)。 | | **方法覆寫** | 不會覆寫方法,因為它是功能的來源類別。| 可以覆寫父類別的方法,以實現新的或特定的行為。| | **關鍵詞** | 常用於建立具有廣泛用途的基底類別 (Base Class)。 | 常用於實現專門化功能,與父類別共享接口 (Interface)。 | | **注意事項** | 若修改父類別,會影響所有繼承該類別的子類別。 | 子類別應遵循父類別的基本結構,否則可能導致程式出現不一致性問題。| | **範例** | `class Animal: ` <br>`def speak(self):` <br>` return "This animal makes a sound." ` | `class Dog(Animal):` <br> `def speak(self):` <br> `return "Woof!"` | * **方法覆寫 (method overriding)**:子類別 (subclass) 重新定義父類別 (superclass) 中已經存在的方法的一種技術。 覆寫的方法在子類別中擁有與父類別相同的名稱和參數,但實現的功能可能不同。這使子類別能根據需求修改或擴展父類別的行為。 ```python # 父類別 class Vehicle: def __init__(self, brand, speed): self.brand = brand self.speed = speed def move(self): return f"The {self.brand} moves at {self.speed} km/h." # 子類別 class Car(Vehicle): def __init__(self, brand, speed, seats): super().__init__(brand, speed) # 呼叫父類別初始化 self.seats = seats def move(self): # 覆寫方法 return f"The {self.brand} car drives at {self.speed} km/h with {self.seats} seats." # 使用繼承 car = Car("Toyota", 120, 5) print(car.move()) ``` ![image](https://hackmd.io/_uploads/SymvmLjmke.png) --- # 額外內容 * json * datatime * csv * decimal * math * os # 工作 - [ ] 把內容潤飾 # reference * 2022資訊之芽 py 語法班 [https://sprout.tw/py2022/slides](https://) * 為你自己學 PYTHON https://pythonbook.cc/chapters/basic/variable * Python 3.13.0 Documentation https://docs.python.org/3/ * PEP-8 Style Guide https://peps.python.org/pep-0008/ * Python 基礎筆記:可變動的(mutable)與不可變動的(immutable) https://medium.com/@oange6214/python-%E5%9F%BA%E7%A4%8E%E7%AD%86%E8%A8%98-%E5%8F%AF%E8%AE%8A%E5%8B%95%E7%9A%84-mutable-%E8%88%87%E4%B8%8D%E5%8F%AF%E8%AE%8A%E5%8B%95%E7%9A%84-immutble-54f1b7a6899 # 圖文編輯寫作要訣 [https://hackmd.io/@robylin/rkgXO18mJx/edit]

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    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

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully