Sam Yang
    • 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
    • Engagement control
    • 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 Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
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
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
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- title: Python 入門教學-資料型態 tags: python_beginner --- # 資料型態 ## 基本概念 * 物件: 在python當中,所有東西都是物件,物件的屬性如下 * identity: 物件的記憶體位置,可用`id()`查看 * type: 物件的類型,可用`type()`查看 * value: 物件的值,分為可變/不可變(mutable/immutable) * immutable: * Numeric types: int, float, complex * string * tuple * frozen set * mutable: * list * dict * set * bytearray > 參考: [理解 Python object 的 mutable 和 immutable](http://wsfdl.com/python/2013/08/14/%E7%90%86%E8%A7%A3Python%E7%9A%84mutable%E5%92%8Cimmutable.html) * 指派變數 在python當中,指派變數可以想像成把一張姓名標籤貼到物件上面。如下例,使用id()印出變數的記憶體位置,觀察兩個變數是否為同一物件: ```python= >>> a = 7 >>> b = a >>> id(a) >>> id(b) ``` 這個例子可以看到,a、b其實是同一個物件"7"。 :::warning 然而看到以下例子: ```python= >>> a = "helloworld" >>> b = "helloworld" >>> id(a) 2917193150576 >>> id(b) 2917193150576 >>> a = "hello world" >>> b = "hello world" >>> id(a) 2917193150576 >>> id(b) 2917193150640 ``` 第一個例子,兩個變數指向同一個字串,然後記憶體位置一樣,這沒問題,跟剛剛看的例子結果一樣。 但是,當我們加入了空格,兩個變數都指向"hello world"時,記憶體位置卻不一樣了。 這是因為python的string interning(字串駐留)機制運作方式的關係。所謂的string interning就是當一個string被命名為某個變數時,python會決定要不要使用之前用過的string,以節省記憶體空間。詳細請看另一篇筆記[Python String Interning機制](https://hackmd.io/lrIcW9cOTj-88G7pSvTyow)。 ::: * 變數命名 * a~z * A~Z * 0~9 * _ 注意: 開頭不可為數字、不可用保留字 查看保留字: ```python= >>> import keyword >>> keyword.kwlist ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'] ``` ### 布林 `True`, `False` ### 數字 * 整數: `2`, `-23`, `1.23e4` 沒有整數溢位問題,可比64bits大 ```python= >>> googol = 10**100 >>> googol 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 >>> googol * googol 100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 ``` * 浮點數 * 運算子 * `+` `-` `*` `/` * `+=` `-=` `*=` `/=` * //: 無條件捨去小數點 * %: 取餘數 * divmod() ```python= >>> divmod(9, 5) (1, 4) ``` * \*\*: 次方 * 基數 * 二進位: 0b * 八進位: 0o * 十六進位: 0x ### 字串 * 使用單引號或雙引號: 可在字串內用單or雙引號,跟最外面的不一樣就好 ```python= >>> "'Hi', said the Tom." 'Hi', said the Tom. >>> '"Hi", said the Jerry.' "Hi", said the Jerry. ``` * 多行字串: `''' '''` 或 `""" """`,會換行 ```python= >>> poem = '''我衰君少年 ... 肚樓夕照前 ... 子爲佛稱名 ... 餓河海暗連''' >>> print(poem) 我衰君少年 肚樓夕照前 子爲佛稱名 餓河海暗連 ``` * \ * \n: 換行 * \t: tab * \\" ```python= >>> "\"I don't understand\"" "I don't understand" ``` * \\\: 如果要用反斜線就在他前面加上反斜線 * +: 連接字串 * \*: 複製字串 ```python= >>> "hi" * 4 'hihihihi' ``` * []: 擷取字串 ```python= >>> letters = "abcdef" >>> letters[0] 'a' >>> letters[-1] 'f' ``` * \[start : end : step\]: Slice * [:] * [start:] * [:end] * [start : end] * [start : end : step] * len() * split() * 更多的東西: help(str()) ## 字串、Ascii轉換 * ord(): 字串轉Ascii ```python= print(ord('a')) ``` * chr(): Ascii轉字串 ```python= print(chr(97)) ``` ## 型別轉換 * int(): 保留整數,捨棄小數 ```python= >>> int(True) 1 >>> int(False) 0 >>> int(87.8) 87 >>> int(1.23e4) 12300 >>> int('99') 99 >>> int('-23') -23 ``` * float() * str()

    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