臺中一中39th電研社教學
      • 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
    • 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 Versions and GitHub Sync Note Insights 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
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- title: Python第三週講義 臺中一中電研社 slideOptions: theme: sky transition: 'convex' --- <style> .blue { color: #000080; } </style> <font color="#000080">Python 第三週講義</font> === >[name= 林德恩、陳睿倬][time= Oct 29,2021 ] ###### tags:`python` `tcirc39th` `社課` `臺中一中電研社` --- ## <span class="blue">電研社</span> 社網:[tcirc.tw](https://tcirc.tw) online judge:[judge.tcirc.tw](https://judge.tcirc.tw) IG:[TCIRC_39th](https://www.instagram.com/tcirc_39th) --- ## <span class ="blue">複習</span> <!--一節課--> ---- ### 補充: 空容器可以直接用: ```python= ls=list() #lists st=set() #sets dn=dict() #dictionanries tp=tuple() #tuple ``` ---- 同行輸出: ```python= print(要輸出的內容,end='間格') #間隔可以沒東西 #間隔是會在句尾輸出 ``` 程式: ```python= for i in range(10): print(i,end='=') ``` output: ``` 0=1=2=3=4=5=6=7=8=9= ``` ---- ### [題目](https://hackmd.io/UYCU7TLPSC65OnxF5t9nyA) --- ## <span class="blue">參考資料</span> [Python 3.10.0 說明文件](https://docs.python.org/zh-tw/3/tutorial/modules.html#the-dir-function/) [模組用法](https://docs.python.org/zh-tw/3/tutorial/modules.html#the-dir-function/) [標準函式庫](https://docs.python.org/zh-tw/3/library/index.html) [Python 模組索引](https://docs.python.org/zh-tw/3/py-modindex.html) --- <!--先抓一些時間複習--> ## <span class="blue">模組 (Module)</span> 模組是由他人之前寫好的程式碼(開源)封裝,並載入我們的程式。如此一來,我們便不用再花時間寫一遍同樣功能的程式。 ---- ### 引入 要使用非內建的程式碼要使用import程式來引用 ```python= import 模組庫名稱 ``` ---- 只import部份 ```python= from 模組庫 import 模組名稱 ``` ---- **縮寫** ```python= import 模組庫名稱 as 縮寫名稱 ``` ---- ### 標準模組 在python下載時一起下載的模組,不用特別下載。 --- ### random <!--https://docs.python.org/zh-tw/3/library/random.html--> 模組庫名稱 ```python= import random ``` ---- #### random.randint(a, b) 此方法會輸出a~b之間(包含a包含b)的隨機整數 ```python= import random as r for i in range(5): print(r.randint(0, 1000)) ``` output ``` 968 815 521 526 865 ``` ---- #### random.random() 此方法和前一個一樣,只是只會輸出介於0~1之間的數字 ```python= import random as r for i in range(5): print(r.random()) ``` output ``` 0.7882666866273765 0.39383355416453714 0.4634658486427745 0.002244936350497384 0.703620193028466 ``` ---- #### random.seed(a = None) 設定random.random()和random.randint()的隨機數字。 若無寫這行程式,每次random函示皆是隨機的,否則會輸出特定數字 若無輸入參數,預設為隨機,參數可以是整數、字串、位元。 最後都會轉為整數 (每次random, randint 使用後便要重新設定) ---- ```python= import random as r for i in range(5): r.seed(10) print(r.randint(0, 1000)) print("======================") for i in range(5): print(r.randint(0, 1000)) # 每次random.randint都會重新設定seed ``` ---- output: ``` 585 585 585 585 585 ====================== 33 439 494 591 15 ``` ---- #### random.randrange(b, e, s) random.randrange(start, stop, step) 和random.randint一樣,但是在特定範圍的等差數列 random.randrange(stop) --> 0 到 end 範圍的每個數字 可想成random.randrange(0, stop, 1) 或random.randint(0, stop) ```python= import random as r for i in range(5): print(r.randrange(1, 9, 2)) #選擇數字 --> [1, 3, 5, 7, 9] ``` ---- output ``` 3 1 7 7 1 ``` ---- #### random.choice(容器) 在輸入的容器裡(list, set, 但dict字典不行)隨機選擇一元素 ```python= import random as r a = ["a", "b", "c"] for i in range(5): print(r.choice(a)) ``` ---- output ``` a c c c a ``` --- ### math ---- #### π ``` math.pi ``` 代表常數π ---- #### math.ceil(x) 回傳≥x的最小整數(無條件進位) ---- #### math.floor(x) 回傳x的無條件捨去 ---- ~~math.round(x)~~ #### round(要四捨五入的值,留到小數點後第幾位) 回傳小數點四捨五入後的x值 ---- #### math.gcd(任意數量的整數並用逗點分隔) ※3.9以前只支援兩個 回傳最大公因數 ---- #### math.lcm(任意數量的整數並用逗點分隔) ※3.9以前沒有 回傳最小公倍數 ---- #### math.sqrt() 參數可以輸入整數型態變數或數字,會輸出開根號後的參數 ---- ```python= import math print(math.gcd(4,6,8)) print(math.lcm(4,6,8)) print("=====") a = 4 print(math.sqrt(a)) a = 6 print(math.sqrt(a)) print("=====") a = 5.6430958 print(math.ceil(a)) print(math.floor(a)) print(round(a)) ``` ---- output ``` 2 24 ===== 2.0 2.449489742783178 ===== 6 5 6 ``` ---- #### math.degrees(x) 將弧度(徑)轉為角度 #### math.radians(x) 將角度轉為弧度(徑) ---- #### 三角函數函式 #### sinθ、cosθ、tanθ ``` math.sin(θ) math.cos(θ) math.tan(θ) ``` ※參數θ為整數變數或數字,注意單位為徑度 ※弧度(徑)=弧長/半徑 ---- ```python= import math as m a = 4 print(m.sin(a)) print(m.cos(a)) print(m.tan(a)) ``` output ``` -0.7568024953079282 -0.6536436208636119 1.1578212823495775 ``` ---- #### **arcsin(sin¯¹)、arccos(cos¯¹)** ``` math.asin(x) math.acos(x) ``` ※參數x為-1~1的數字,為sinθ或cosθ的值 回傳sin¯¹x(arcsin x)或cos¯¹x(arccos x)的值 acos結果會在-π\~π之間asin則是在-π/2\~π/2之間 <!--要如何解釋--> ---- #### **arctan(tan¯¹)、atan2** ``` math.atan(x) ``` ※參數x為-1~1的數字,為tanθ的值 回傳tan¯¹x(arctan x) ※atan回傳值是在-π/2\~π/2之間 ``` math.atan2(y,x) ``` 回傳atan(y/x) --- <!--不一定要教完--> ### fractions(分數) ``` class fractions.Fraction(整數, 整數) class fractions.Fraction(數字或字串(只有數字和空白)) ``` 回傳最簡分數 ```python= from fractions import Fraction Fraction(" 1.25 ") Fraction(15,45) ``` ---- **output** ``` 5/4 1/3 ``` --- <!--不一定要教完--> ### statistics ``` statistics.mean(序列) ``` 回傳平均數 ``` statistics.fmean(序列) ``` 轉為浮點數並回傳平均數(比mean快) --- ## <span class="blue">擴充程式庫</span> 如果我們要將網路上由其他人寫的python模組(非官方提供的)載入並使用,我們得先安裝。 安裝的方法得去各開源的官方網站查詢。 *若不想安裝則可使用google提供的google colab實作* ---- ### NumPy NumPy是Python語言的一個擴充程式庫。支援高階大量的維度陣列與矩陣運算,此外也針對陣列運算提供大量的數學函式函式庫。 在AI演算及大數據分析常用到 [Numpy教學](https://blog.techbridge.cc/2017/07/28/data-science-101-numpy-tutorial/) ---- ### ndarray 陣列是numpy最大的優點,他可以快速地運算大量的資料。 建立一維陣列(1-D) ```python= import numpy as np arr1 = np.array([1, 2, 4]) print(arr1) print(type(arr1)) ``` output ``` [1 2 4] <class 'numpy.ndarray'> ``` ---- 2-D Array ```python= import numpy as np arr1 = np.array([[1, 2, 4], [5, 7, 8]]) print(arr1) print(type(arr1)) ``` output ``` [[1 2 4] [5 7 8]] <class 'numpy.ndarray'> ``` ---- 3-D Array ```python= import numpy as np arr1 = np.array([ [ [1, 2, 4], [5, 7, 8] ], [ [1, 2, 4], [6, 4, 7] ] ]) print(arr1) print(type(arr1)) print(arr1.ndim) # check arr1 dimensions(維度) ``` output ``` [[[1 2 4] [5 7 8]] [[1 2 4] [6 4 7]]] <class 'numpy.ndarray'> 3 ``` ---- 我們也可子直接設定陣列維度 ```python= import numpy as np arr1 = np.array([1, 3, 5], ndmin = 6) print(arr1) print(type(arr1)) print(arr1.ndim) # check arr1 dimensions(維度) ``` output ``` [[[[[[1 3 5]]]]]] <class 'numpy.ndarray'> 6 ``` ---- #### 拜訪元素 我們要訪問陣列元素和python的list一樣用中括號[idx]拜訪 ```python= import numpy as np arr1 = np.array([1, 2, 4, 8, 6, 3, 9]) print(arr1) print(type(arr1)) print("arr1 7th element is =", arr1[6]); ``` output ``` [1 2 4 8 6 3 9] <class 'numpy.ndarray'> arr1 7th element is = 9 ``` ---- 拜訪二維陣列元素 不同於list[idx1][idx2]... ndarray是[idx1, idx2, ....]表示 ```python= import numpy as np arr1 = np.array([ [1, 5, 6], [4, 7, 8] ]) print(arr1) print(arr1[0, 2]) # 二維陣列中的第一個陣列的第3個元素 ``` output ``` [[1 5 6] [4 7 8]] 6 ```

    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