臺中一中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 New
    • Engagement control
    • Make a copy
    • 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 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
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第二週講義 臺中一中電研社 slideOptions: theme: sky transition: 'convex' --- <style> .blue { color: #000080; } .silver { color: #c0c0c0; } .white{ color: #ffffff; } </style> *[Ans]: https://hackmd.io/6GLKoqcMQbGwJ961iE5hCw (學弟們有帶電腦的要裝python,建議裝個IDE,推薦用visual studio code或visual studio2019) <font color="#000080">Python 第二週講義</font> === >[name= 林德恩、陳睿倬][time= Oct 15,2021] ###### tags:`python` `tcirc39th` `社課` `臺中一中電研社` --- [TOC] ## <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">None</span> None是一個值代表沒有值,但還是佔一個位子。 ※不是空白 --- ## <span class="blue">容器型態</span> 容器是用來儲存多個變數用。 而部分的容器都有序號 而編號從0開始 ---- 字串也可以算是一種容器,所以可以指定位址。 ```python= 字串變數[編號] ``` ---- ### 清單(Lists) 可儲存不同型態的元素,也可修改裡面元素(可把它想成書櫃) ```python= #list名稱 = [元素1, 元素2, 元素3...] arr = [1, 2, 4, string, 7, True, 0.9] ``` ---- #### 訪問元素 如果想要知道特定list中第幾個元素 idx(序號) 0 1 2 3 4 list = [1, 6, 7, 3, 8] ```python= arr = [1, 2, 4, string, 7, True, 0.9] print(arr[0]) # 注意: list的第一個元素的序號為0 ``` output ``` 1 ``` ---- #### append() 若要增加元素,則使用append()功能 ※*會加到最後面* ```python= arr = [1, 2, 4, "string", 7, True, 0.9] print(arr) arr.append(5) arr.append("txt") print(arr) ``` **output** ``` [1, 2, 4, 'string', 7, True, 0.9] [1, 2, 4, 'string', 7, True, 0.9, 5, 'txt'] ``` ---- #### pop() 若要刪除元素,則使用pop功能 ```python= arr = [1, 4, 3, 2, 6] print(arr) arr.pop(2) # 刪除序號為四的元素,後面元素往前遞補 print(arr) arr.pop() # 若無輸入序號,則刪除最後一項 print(arr) ``` output ``` [1, 4, 3, 2, 6] [1, 4, 2, 6] [1, 4, 2] ``` ---- #### len() ```python= arr = [1, 3, 4, 2, 6] print(len(arr)) ``` output ``` 5 ``` ---- #### clear() clear()功能能清除list內的所有元素 ```python= arr = [1, 3, 4, 2, 6] print(arr) arr.clear() print(arr) ``` output ``` [1, 3, 4, 2, 6] [] ``` ---- #### insert() 若要插入元素至list的特定位置,則使用insert功能 使用方法為insert(序號, 要插入的東西) ```python= arr = [1, 3, 4, 2, 6] print(arr) arr.insert(1, 5) print(arr) ``` output ``` [1, 3, 4, 2, 6] [1, 5, 3, 4, 2, 6] ``` ---- #### index() 若要搜尋list內的特定元素在第幾個序號,則使用index()功能 index(要查詢的元素) **!!注意,搜尋的值必須確定存在於list裡,否則會程式會顯示錯誤** ```python= arr = [1, 3, 4, 2, 6] print(arr) idx = arr.index(4) print(idx) ``` output ``` [1, 3, 4, 2, 6] 2 ``` ---- 錯誤示範 ```python= arr = [1, 3, 4, 2, 6] print(arr) idx = arr.index(7) print(idx) ``` output ``` [1, 3, 4, 2, 6] Traceback (most recent call last): File "<string>", line 3, in <module> ValueError: 7 is not in list ``` ---- #### sort() 若要對list內的元素進行排序,則使用sort()功能 **!!注意如果要使用sort功能,list內的不可有數字和字串並存** ```python= arr = [1, 6, 3, 8, 5.6] print(arr) arr.sort() print(arr) ``` output ``` [1, 6, 3, 8, 5.6] [1, 3, 5.6, 6, 8] ``` ---- 字串排序 ```python= arr = ['a', 'o', 'd', 'e' ] print(arr) arr.sort() print(arr) ``` output ``` ['a', 'o', 'd', 'e'] ['a', 'd', 'e', 'o'] ``` ---- 空list可以直接用: ```python= ls=list() #lists ``` ---- ### 字典(Dictionaries) 功能類似list,但元素無序號。取而代之的是key,key值須自己設定,且不能有重複key值(但可有重複元素) 數字、字串、元組(tuple)...皆可作為key ```python= """ dict = { key1 : value1 key2 : value2 . . . } """ dic = { "year" : 1992, "name" : "???" } print(dic["name"]) dic["name"] = "tcfsh" #修改key所對應的值 print(dic["name"]) dic["type"] = "senior_highschool" #新增一個key和其對應的值 print(dic["type"]) ``` ---- output ``` ??? tcfsh senior_highschool ``` ---- 其他型態的key ```python= dic = { 1:5, "six":6, (1, 4):8 } print(dic) ``` output ``` {1: 5, 'six': 6, (1, 4): 8} {1: 5, 'six': 6, (1, 4): 8} ``` ---- #### clear() 功能和list的clear()功能一樣,清空字典裡的所有元素 ```python= dic = { "year" : 1992, "name" : "???" } print(dic) dic.clear() print(dic) ``` output ``` {'year': 1992, 'name': '???'} {} ``` ---- #### pop() 功能和list一樣,刪除特定元素的key和對應的值 pop(要刪除的key) ```python= dic = { "year" : 1992, "name" : "???" } print(dic) dic.pop("year") print(dic) ``` ouput ``` {'year': 1992, 'name': '???'} {'name': '???'} ``` ---- 空字典可以直接用: ```python= dn=dict() #dictionanries ``` ---- ### 集合(Sets) 在python裡,集合是一個無順序的容器,且不能儲存重複元素 ```python= myset = {"apple", "banana", "cherry"} print(thisset) ``` output ``` {'cherry', 'banana', 'apple'} ``` ---- #### add() 若要增加元素至set裡,用add()功能 ```python= myset = {"apple", "banana", "cherry"} print(myset) myset.add("mango") print(myset) ``` output ``` {'apple', 'banana', 'cherry'} {'mango', 'apple', 'banana', 'cherry'} ``` ---- 空sets可以直接用: ```python= st=set() #sets ``` ---- ### 元組(Tuple) 功能和list類似,但初始化後便不能再更改 ```python= #tuple名稱 = (元素1, 元素2....) mytuple = (1, "banana", True) ``` ---- 空元組可以直接用: ```python= tp=tuple() #tuple ``` --- ## <span class="blue">分割</span> split函式(部分功能說明) 因為python沒有內建同行以空白分隔兩個值,而且很多題目都需要用到這個功能,所以說明一下python如何處理。 ```python= 要分割的文字變數.split("要判斷分割的符號") #括號內不加任何東西就預設為空白 ``` 使用 ```python= 容器 或 多個變數(要和分割結果一樣多) = 要分割的變數.split("要判斷分割的符號") #推薦使用容器 ``` *※因分隔前是文字,所以分割後也是文字* ---- **程式** ```python= a = [None] i = input() a = i.split() print(a) ``` ---- ## <span class="blue">同行輸出</span> ```python= print(要輸出的內容,end='間格') #間隔可以沒東西 #間隔是會在句尾輸出 ``` 程式: ```python= for i in range(10): print(i,end='=') ``` output: ``` 0=1=2=3=4=5=6=7=8=9= ``` --- ## <span class="blue">運算子</span> ### <span class = "silver">+</span>&<span class = "silver">-</span>&<span class = "silver">×</span>&<span class = "silver">÷</span>&<span class = "silver">次方</span>&<span class = "silver">取餘(%)</span>&<span class = "silver">取商(//)</span> ---- ### 比較運算子 用於判斷是否達成條件,結果為布林值 ---- #### =(==) 兩個值是否相等 ※ <span class= "silver">=</span> *是定義資料的值* ```python= 資料==資料 ``` #### ≠(!=) 兩個值是否不相等 ```python= 資料!=資料 ``` ---- #### >、<、≥(>=)、≤(<=) ```python= 數值>數值 數值<數值 數值>=數值 數值<=數值 ``` ---- **範例** ```python= print("123"=="345") print("1234"!="1234") print(1>2) print(1<=2) ``` **output** ``` False False False True ``` ---- ### 邏輯運算子 and(且): **布林值 and 布林值** or(或):**布林值 or 布林值** not(非):**not 布林值** ---- ```python= print(True and False) print(True or False) print(not False) ``` **output** ``` False True True ``` ---- ### 位元邏輯運算子 **logic shift** 將其二進為表示的數字左移或右移n位 ```python= 數值<<n 數值>>n ``` ---- **&(and位元運算)** 將兩個數值的二進位數值進行and運算 ```python= 數值&數值 #10&01 == 00 ``` **|(or位元運算)** 將兩個數值的二進位數值進行or運算 ```python= 數值|數值 #10|01 == 11 ``` ---- **~(not位元運算)** 將其二進位數值進行not運算 ```python= ~數值 #因python是用二補負法做正負判斷 #所以0(假設是000)進行not運算會變-1(111) #二補負法不會因儲存的位元不同而使not運算結果改變 ``` **^(xor位元運算)** 將兩個數值的二進位數值進行xor運算 ```python= 數值^數值 #10^11 == 01 ``` ---- **二補負法**: 設有3bit的空間 000→0 011→3 到一半時(1後全為0)轉為最小的負數繼續加一 100→-4 111→-1 優點:可以直接進行加減 ---- **範例程式** ```python= logic = True #1 number = 39 #100111 print(logic << 3) number = number >> 2#1001 print(number) print(3|9)#11 1001 print(~6) ``` **output** ``` 8 9 11 -7 ``` --- ## <span class="blue">運算式</span> 任何可以取得值的程式碼,都可以稱為運算式。 ---- ### 條件運算式 在判斷值為True或False後決定要執行的程式 ---- **if** 是否達成條件,若有,則執行下方程式 ```python= if (條件): #coding ``` ---- **else** *前面要先有 if 函式* 未達成上方if的條件時,執行下方程式 ```python= if (條件): else: #coding ``` ---- **elif(else if)** *前面要先有 if 函式* 未達成上方if的條件時,判斷是否達成此條件,若有,執行下方程式 ```python= if (): #coding elif (): #coding elif (): #coding else: #coding ``` ---- **三元運算子** 和if else功能差不多,但程式碼較短(一行) *可以連用* ```python= 達成條件後執行 = if 條件 else 否則執行 ``` ---- ~~switch~~ 判斷指定條件,依照不同結果執行不同程式 ```cpp= switch(變數或運算式) { case 條件的結果1: //是冒號 程式; break; //一定要加,否則會繼續往下執行 case 條件的結果2: 程式; break; default: //其他 程式 break; } ``` ***python沒有switch*** ---- **程式** ```python= a=0 b=1 if(a==b): print(a) elif(a<b): print(b) else: print("123456") ``` **output** ``` 1 ``` ---- ### 練習 [b012: 不及格的危機](https://judge.tcirc.tw/ShowProblem?problemid=b012) --- ## <span class="blue">迴圈</span> 迴圈是用來進行重複執行時的工具,它在不符合指定的條件前,除非強制跳出否則不會停止。 ---- ### while while會重複執行到條件**不**達成為止。 ```python= while (條件): 程式 ``` ---- ### for for迴圈也會重複執行到條件**不**達成為止,但它可以直接設定次數。 ```python= for 變數 in 有編號的容器 或 range函數 ``` 變數可以不用先設定,而每次for迴圈開始就會加一。 變數的值會因後方的變數而改變。 ---- **使用range函數** ```python= for 變數 in range(起始值, 終止值, 公差): #變數會從起始值開始 #coding ``` ---- **range函數** ```python= range(起始值,終止值,差) #只能輸入整數型態 #起始值可不寫(起始值會為0) #差可不寫(差會為1) ``` ---- **使用容器** ```python= for 變數 in 字串: #因為字串也是容器一種 程式 或 for 變數 in list: #只要有序號的容器 程式 ``` ---- **程式** ```python= s=[4,5,6,"a","b"] for i in range(-1,10,3): print(i) for k in "list": print(k) for n in s: print(n) for x in range(0,5): for y in range(x): print(y) ``` ---- **output** ``` -1 2 5 8 l i s t 4 5 6 a b 0 0 1 0 1 2 0 1 2 3 ``` ---- ### break 跳出當前迴圈 ```python= 迴圈 break ``` ---- ### continue 會跳過後方要執行的程式從迴圈最上方的程式開始 ```python= 迴圈 程式 #可寫可不寫 continue 程式 #會被跳過 ``` ---- **程式** ```python= for i in range(0,5,1): print('1') if(i>3): continue print('2') a=0 print("-------") while(a<5): a+=1 b=0 while(b<3): b+=1 print(str(a)+str(b)) if(a==2): print("-------") break ``` ---- **output** ``` 1 2 1 2 1 2 1 2 1 ------- 11 12 13 21 ------- 31 32 33 41 42 43 51 52 53 ``` ---- **練習** [b036: 物種豐富度](https://judge.tcirc.tw/ShowProblem?problemid=b036) [<span class="white">Ans</span>](https://hackmd.io/6GLKoqcMQbGwJ961iE5hCw)

    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