中興大學資訊社
      • 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
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners 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
    • Transfer ownership
    • Delete this note
    • 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 Help
Menu
Options
Engagement control 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
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners 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
    --- title: 函式庫 - Python 教學 description: 中興大學資訊研究社1101學期程式分享會主題社課 tags: Python --- ###### [Python 教學/](https://hackmd.io/7-LP9CyOThOdkEbq44FLvw) # 函式庫(套件) > [name=VJ][time= 109,11,26] > [name=HuiXillya][time= 110,12,2] --- ## 什麼是函式庫? 函式庫在Python 中叫做**套件**,意思是一樣的。 函式庫可以是一個文件,包含了一系列你想引用在你的目前程式中的函式。 --- ## 建立套件 要建立一個套件(函式庫),只需將你想要的程式碼保存在一個副檔名為 `.py` 的文件中。 例如我們將上次寫出來用作印出直角三角形的程式碼存成 `mymodule.py` 。那麼這個套件就叫做 `mymodule`。 ```python= def rTr(n:int): for i in range(n): for j in range(i): print('*',end='') print() ``` --- #### 練習1 試著將上程式碼的函式寫成函式庫,並執行 >在本地新增文字檔,附檔名要叫 py >記得要打檔案丟到colab旁邊的檔案區 --- ## 引用套件 我們可以用 `import` 關鍵字來引用我們剛剛創建的 `mymodule` 套件,從而使得我們可以使用裡面的函式。 注意: 存檔時目錄要相同才能引用。 ```python= import mymodule mymodule.rTr(5) ``` 注意:當使用套件中的函式時,請使用語法:`mod.func()`。 --- ## 套件中的變數 套件可以像上面包含函數,也可以包含各種類型的變數(串列、字典、物件等),當然也可以被引用。 例如我們將下面的字典存成 `mymodule.py` ```python= person1 = { "name": "John", "age": 36, "country": "Norway" } ``` --- 然後引用名為 `mymodule` 的套件,接著存取字典 `person1`。 ```python= import mymodule a = mymodule.person1["age"] print(a) #輸出: 36 ``` --- #### 練習2 試著將上程式碼中的字典加入函式庫,並使用 --- #### 練習3 下載[NCHUIT.py](https://drive.google.com/file/d/1C3aTkZsC-Lr4Pn7AcxtKu4rox-mJO1L3/view?usp=sharing )並執行其中的 hello 函式 --- #### 練習4 修改 [NCHUIT.py](https://drive.google.com/file/d/1C3aTkZsC-Lr4Pn7AcxtKu4rox-mJO1L3/view?usp=sharing ) 的 hello 使其呼叫時印出 'hello world!' >.py用記事本或者vscode打開 --- ## 重新命名套件 我們可以用 `as` 關鍵字來創建一個**別名**。通常用來縮短程式碼。 例如為剛剛函字典的套件 `mymodule` 創建一個名為 `mx` 的別名。 ```python= import mymodule as mx a = mx.person1["age"] print(a) #輸出: 36 ``` --- ## 列出所有可以用的東西 用 `dir()` 函數可以列出一個套件中所有的函數(或變數)。 ```python= import platform x = dir(platform) print(x) ``` 注意:`dir()` 函數所有套件都可以用,自己存的套件也可以用。 --- #### 練習5 列出 NCHUIT 裡的所有東西 --- ### help() >有時候不是不會寫,只是需要一點點小小的提示 各位在使用function時會不會忘記要傳甚麼引數進去? 或者忘記會回傳甚麼 讓help幫幫你 ```python= help(print) #不要打括號,我們是把'print'傳入,不是呼叫 ``` 同時,也是你打到一半會跑出來的提示 ![](https://i.imgur.com/7q4w5B9.png) #### 練習6 查看 NCHUIT 的說明 之後看看裡面各種函式的說明 #### 練習7 新增 hello 的提示 >可跳過 >參考一下其他函式的寫法 --- ## 內建套件 在Python中,有幾個內建套件,隨你引用。 例如引用並使用 `platform` 套件。 ```python= import platform x = platform.system() print(x)#輸出目前的作業系統 ``` --- ### random https://docs.python.org/zh-tw/3/library/random.html > random.seed(a=None, version=2) > 初始化随机数生成器。 > > 如果 a 被省略或为 None ,则使用当前系统时间。 如果操作系统提供随机源,则使用它们而不是系统时间(有关可用性的详细信息,请参阅 os.urandom() 函数)。 >random.randint(a, b) >返回随机整数 N 满足 a <= N <= b。相当于 randrange(a, b+1)。 範例: 輸出隨機一個1~n的整數 ```python= import random n=10 random.seed() print(random.randint(1, n)) ``` #### 練習8 假設骰子有1-6點,擲出每種點數的機率都是1/6 輸入整數n,回傳投n顆骰子的點數 #### 練習8.5 修改上述的程式碼,使之回傳n顆骰子擲m次的分布情形 ### time https://docs.python.org/zh-tw/3/library/time.html >交給你們了,自己試試看 #### 練習9 倒數計時器 輸出n 至 0 (一秒輸出一個字) >hint 搜尋'sleep' ## 安裝套件 ```bash pip˽install˽套件名稱1[˽套件名稱2˽...(選用)] ``` ### 範例1 matplotlib 製圖作表 ```python= import matplotlib.pyplot as plt dic={0:0} for i in range(50): dic[i]=i+1 plt.bar(list(dic.keys()),list(dic.values()), color='b') plt.show() ``` #### 練習6 把剛剛練習8.5的數值放入圖表中 製作分布圖 ### 範例2 requests && beautifulsoup4 可發送http請求,並解析 ```bash=! pip install --upgrade pip requests beautifulsoup4 ``` 在colab的環境下 上述指令前面都須加上驚嘆號 如: ```bash=! ! pip install --upgrade requests beautifulsoup4 ``` #### 西洽爬蟲 ```python3= import requests import bs4 respone = requests.get(url='https://www.ptt.cc/bbs/C_Chat/index17616.html') respone.encoding = 'utf-8' root = bs4.BeautifulSoup(respone.text, 'html.parser') titles = root.find_all('div',class_='title') for x in titles: t = x.find('a') if t: print(t.string) ``` --- ## 解除安裝套件 ```bash=! pip uninstall -y openpyxl tablepyxl requests beautifulsoup4 django line-bot-sdk Pillow IPython pytz numpy flask ``` ###### 注意: 請不要解除安裝 pip --- <style>hr{display:none;}</style>

    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