Cracked Head
    • 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
    # 2. 資料型態與基本運算 ###### tags: `Python` - Python 教學 第二篇 資料型態與基本運算 ::: info 以下程式碼無先後順序 無連貫性 推薦影片教學頻道: - 英文 : [Tech With Tim](https://www.youtube.com/c/TechWithTim/featured) - 中文 : [彭彭老師的程式教學](https://www.youtube.com/watch?v=wqRlKVRUV_k&list=PL-g0fdC5RMboYEyt6QS2iLb_1m7QcgfHk&index=1&t=24s) ::: ## 一、資料型態 Data-types: ||資料的種類|| |:-:|:-:|:-:| |變數|整數|浮點數| |字串|布林值|可變列表| |固定列表|集合|字典| ### 1. 變數 variable - 用來儲存資料的自訂名稱物件 #### (1) 變數的命名限制: - 1. 小寫字母(a~z) - 2. 大寫字母(A~Z) - 3. 數字(0~9) - 4. 底線(_) - 5. 不能以數字作為開頭,如 92s - 還有Python預設的關鍵字 Keywords 也不可被用來作為變數名稱 這些關鍵字我將會在 第五篇 -函數的使用 中逐一介紹 ||||||| |:------:|:------:|:--------:|:------:|:------:|:-------:| | and | del | for | is | raise | assert | | elif | from | lamba | return | break | else | | global | not | try | while | def | finally | | in | print | continue | exec | import | pass | | class | except | if | or | yield | | ||||||| #### (2) 以下是一些合法的命名: 1. x 2. y 3. a 4. a_b 5. a32 6. _fe1 ::: info 以下宣告 / 定義 變數後 大家可以自己試試看使用type功能 / 函數: - type(變數名稱) 可以取得變數所儲存的 資料 的 資料型態 - print(type(變數名稱)) 印出變數的資料型態 ::: ### 2. 整數 int - 不會有小數點,會將小數點後的數字無條件捨去 ```python= # 將整數10儲存到變數x當中 x = int(10) # 由於10.9487被定義為整數int,小數無條件捨去,變為10,然後儲存到變數x,所以x依然會是 10 x = int(10.9487) print(type(x)) #用type()函式/功能 取得 x 的資料型態並印出 => <class "int"> ``` ### 3. 浮點數 (小數) float - 一定會有小數點,被宣告時如果使用float,就算是整數依然會視為浮點數 ```python= # 將整數10以浮點數型態儲存到變數x當中,x 等於 10.0 x = float(10) # 由於10.9487為浮點數,儲存到變數 x 後,x 等於 10.9487 x = 10.9487 # 由於10.9487被定義為浮點數float,小數保留,儲存到變數x,所以 x 等於 10.9487 x = float(10.9487) print(type(x)) #用type()函式/功能 取得 x 的資料型態並印出 => <class "float"> ``` ### 4. 字串 string: - 由單 / 雙引號包裹住的任意字元 包括整數、浮點數,只要由單 / 雙引號包裹住,就是字串 #### (1) 字串基礎 ```python= # Hello World! 英文字元、空格與驚嘆號 包裹在雙引號中 儲存到變數x x = "Hello World!" print(x) #印出 "Hello World!" # 哈囉 世界! 英文字元、空格與驚嘆號 包裹在單引號中 儲存到變數x x = '哈囉 世界!' print(x) #印出 "哈囉 世界!" # 數字字串 浮點數字串也同理 皆用單 / 雙引號包裹 x = "1 2 4 5 9 8 10 88 92" #1 2 4 5 9 8 10 88 92 全都是字串 不是數字 # 將整數94轉換成字串型態 並儲存到變數x x = str(94) #等於 x = "94" # 浮點數同理 x = str(94.53) #等於 x = "94.53" print(type(x)) #用type()函式/功能 取得 x 的資料型態並印出 => <class "str"> ``` #### (2) 字串轉換符 在字串內使用特殊符號,如: 字串內使用單引號、雙引號、縮排、歸位、換行 ```python= "\\" # 單斜線 \ "\'" # 單引號 ' "\"" # 雙引號 " "\t" # 縮排 => Tab 縮排 => 4個空格 "\r" # 歸位 => 等於方向鍵一直移到該行最前端 從最前端開始輸出 並且會覆蓋之前的輸出 "\n" # 換行 => 換行 ``` #### (3) 格式化字串 將變數資料插入字串當中 ```python= name = "LeeFuuChang" age = 17 x = "My name is {}, and I am {} years old".format(name, age) #照順序放入變數 # 則 x = "My name is Ivan, and I am 17 years old" # 也可以給與位置名稱 並依照對應名稱放置變數 x = "My name is {Name}, and I am {myAge} years old".format(myAge=age, Name=name) # x 一樣等於 "My name is Ivan, and I am 17 years old" # 另外還有 f字串 可以直接相變數插入字串 x = f"My name is {name}, and I am {age} years old" # x 也一樣等於 "My name is Ivan, and I am 17 years old" ``` ### 5. 布林值 bool: - True 和 整數 1 代表 是、正確 ```python= #True 的表示法 x = True print(type(x)) #用type()函式/功能 取得 x 的資料型態並印出 => <class "bool"> #同時 整數 1 也可以用來代表True int(1) ``` - False 和 整數 0 代表 否、不正確 ```python= #False 的表示法 x = False print(type(x)) #用type()函式/功能 取得 x 的資料型態並印出 => <class "bool"> #同時 整數 0 和 None 也可以用來代表 False int(0) None ``` ### 6. 可變列表 list: - 有順序的 可變更的列表 List 在宣告後可以新增 / 刪減列表中的物件 - [ 物件 1 , 物件 2 , 物件 3 , 物件 4 , 物件5 ] => 列表 - [  0   ,  1   ,  2   ,  3   ,  4  ] => 列表位置 第一個物件為0 第二個為1 以此類推 ```python= #第 N 個物件 的位置為 N-1 # a 是一個空的List a = list() # a 是一個List 有五個物件 分別是True, 整數2, 字串3, 整數4, 字串5 a = [True,2,"3",4,"5"] # 同上 a 是一個List 有五個物件 分別是 True, int(2), str(3), float(4), str(5) a = list([True,2,"3",4.0,"5"]) # a 是一個List 有五個物件 分別是 True, int(2), str(3), float(4), str(5) a = [True,2,"3",4,"5"] a.append("hehe") #在 a 列表的最後新增一個物件 "hehe" a.remove(2) #移除列表中最前面的一個 int(2) a.pop(3) #移除列表中第4個物件 如果沒有指定 => a.pop() 則會移除列表中最後一個物件 a.clear() #清空列表 del a[0] #移除列表中第1個物件 如果沒有指定 => del a 則會完全清除變數a 也就是a 不再是變數 ``` ### 7. 固定列表 tuple: - 有順序的 不可變更的列表 Tuple 在宣告後不可改動列表中的物件 #### !!!!! Tuple 可合併 不可更動物件 不可新增物件 不可移除物件 !!!!! ```python= # 舉例來說 a = (1, 4, "9", "Hello", True, False) # 則 a 除非被清除 否則永遠等於 (1, 4, "9", "Hello", True, False) # 除非變數 a 被清除 否則 a[0] 永遠是 int(1) # 除非變數 a 被清除 否則 a[1] 永遠是 int(4) # 除非變數 a 被清除 否則 a[2] 永遠是 str(9) # 除非變數 a 被清除 否則 a[3] 永遠是 "Hello" # 除非變數 a 被清除 否則 a[4] 永遠是 True # 除非變數 a 被清除 否則 a[5] 永遠是 False ``` ### 8. 集合 set: - 無順序的 不可變更的 物件不重複的列表 Set 在宣告後不可改動列表中的物件 #### !!!!! Set 內的物件 [ 不重複 ] [ 無順序 ] !!!!! ```python= #Set內的物件 [ 不重複 ] [ 無順序 ] # 定義 a 為一個Set a = {5,5,1,"he","she","it",False} # 由於 Set的不重複性 # a 列表中的物件會只剩下 1, 5, "he", "she", "it", False # 又因為 Set的無順序性 列表中物件的順序將被打亂 # 最後 a 會變成這樣 {False, 1, 'it', 5, 'she', 'he'} 且每次執行都不一樣 # 通常使用於將原先就存在的一個列表List 轉為Set 使其物件單一 / 打亂順序 a = [1,10,10, "hello", "gg",False] a = set(a) ``` ### 9. 字典 dict: - 有順序的 可變更的 物件不重複的對照型列表 Dictionary 在宣告後不可改動列表中的物件 - 每個物件都有兩個值 分別為 key 和 value 一個key會對應一個value - key 不可重複 value 可重複 #### !!!!! Dictionary 內的物件: [ 不重複 ]、[ 有順序 ]、[兩兩成對] !!!!! ```python= # 定義 a 為一個 Dictionary a = {"key": "value", "key1": "value1", "key2":"value2", "key3":"value3"} # a 的 物件有 # "key": "value" # "key1": "value1" # "key2":"value2" # "key3":"value3" # 舉例 a = {"a":"apple", "b":"banana", "c":"cow", "d":9487} # a["a"] 等於 "apple" # a["b"] 等於 "banana" # a["c"] 等於 "cow" # a["d"] 等於 int(9487) ``` ## 二、 數字 列表 字串 的運算 ### 1. 運算子的種類 ||運算子|作用|舉例|可用於| |:-:|:-:|:-:|:-:|:-:| |1.|+|相加|a+b|數字 and 字串 and 列表List| |2.|-|相減|a-b|數字| |3.|*|相乘|a*b|數字 and 字串 and 列表List| |4.|/|相除|a/b|數字| |5.|%|取餘數|10%3 得 1|數字| |6.|**|次方|a**b a的b次方|數字| |7.|//|取整數商|10//3 得 3|數字| |8.|+=|加等於|a+=b 等於 a=a+b|數字 and 字串 and 列表List| |9.|-=|減等於|a-=b 等於 a=a-b|數字| |10.|*=|乘等於|a*=b 等於 a=a*b|數字 and 字串 and 列表List| |11.|/=|除等於|a/=b 等於 a=a/b|數字| |12.|==|等於|a == b|數字 and 字串 and List| |12.|>|大於|a > b|數字| |13.|<|小於|a < b|數字| |14.|>=|大於等於|a >= b|數字| |15.|<=|大於小於|a <= b|數字| ### 2. 數字運算 ```python= # 定義變數值 a = 10 b = 5 #數字運算舉例 c = a + b # c=15 c = a - b # c=5 c = a * b # c=50 c = a / b # c=2.0 => 整數型態變數經過除法運算後不論是否整除都會變成浮點數型態 c = a % b # c=0 => 整除 c = a // b # c=2 => 雖是除法 但只取整數 所以當然是整數型態 c = a += b # c=15 c = a -= b # c=5 c = a *= b # c=50 c = a /= b # c=2.0 a > b # True => a的確大於b 所以輸出布林值 True a < b # False => a並不小於b 所以輸出布林值 False a >= b # True => a的確符合大於或等於b 所以輸出布林值 True a <= b # False => a並不小於或等於b 所以輸出布林值 False ``` ### 3. 字串運算 ```python= # 定義變數值 a = "Hello" b = "World" i = 4 #字串運算舉例 c = a + b # c="HelloWorld" => 字串合併 c = a * i # c="HelloHelloHelloHello" => 重複四次a c = a += b # c="HelloWorld" => 字串合併 c = a *= i # c="HelloHelloHelloHello" => 重複四次a a == b # False => 兩個變數儲存的字串並不同 所以輸出布林值 False ``` ### 4. 列表運算 (List) ```python= # 定義變數值 a = ["hello", "world"] b = ["JJJ", "5566"] i = 3 #列表運算舉例 c = a + b # c=["hello", "world", "JJJ", "5566"] => 列表合併 c = a * i # c=["hello", "world","hello", "world","hello", "world"] => 重複三次 c = a += b # c=["hello", "world", "JJJ", "5566"] => 列表合併 c = a *= i # c=["hello", "world","hello", "world","hello", "world"] => 重複三次 a == b # False => 兩個變數儲存的列表並不同 所以輸出布林值 False ``` ### [上一篇](https://hackmd.io/hR-7Aq8OSM26QJbSgIxGCw?view) ### [下一篇](https://hackmd.io/UGzZn3f6Sge-HI1EVx6MWg?view)

    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