SiriusKoan
    • 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
    --- tags: Sprout type: slide --- # 第一階段複習 siriuskoan --- ## Outline - 變數與型別 - 邏輯判斷 `if` - 迴圈 `for`、`while` - string - `list` - `dict` - 函式 - module --- ## 先複習一下 IO ```python= name = input("輸入名字: ") print("Your name is", name, sep=" ", end="!") ``` --- ## 變數與型別 變數是存放值的容器 型別代表這個變數(值)的類型 ---- ## 型別 - `int` - `str` - `float` - `list` - ... ---- ## 運算子 - `+`、`-`、`*`、`/`、`//` - `&`、`|`、`^`、`~` - `and`、`or`、`not` ---- ## 範例 ```python= # int a = 1 a2 = a + 5 a3 = a2 * 2 # float b = 1.0 # str c = str(a) c *= 10 # list d = [1, "1"] ``` ---- ## Quiz *階段考不會出現* What's the output? ```python= a = 12 a = str(a) a1 = int(a) + 1 a2 = a * 2 a3 = int(a) + 3 // 2 print(a1, a2, a3) print(type(a1), type(a2), type(a3)) ``` --- ## 邏輯判斷 `if` 判斷一個條件是否為真,並根據結果做不同的事情 ---- ## 範例 ```python= score = int(input("輸入分數: ")) if score >= 90: print("A+") elif score >= 85: print("A") elif score >= 80: print("A-") else: print("no A") ``` ---- ## `=` vs. `==` - `=` - 賦值 - 把一個變數的值設定成某個值 - `==` - 判斷 - 判斷兩個值是不是相同 ---- ## Quiz What's the output? ```python= # credit to 鄧人豪 x = 2 y = 3 bool1 = x == y bool2 = x = y print(bool1, bool2) print(x, y) ``` --- ## 迴圈 `for`、`while` 在某個條件成立時重複執行特定片段的程式 - `while` - 通常在有一個確定條件來決定是否要迴圈時使用 - 如: `name == ""` - `for` - 通常在確定(常數或是變數都可以)要跑幾次的時候使用 - 如: 倒數計時器 ---- ## 範例 ```python= # while name = input("請輸入名字: ") while name == "": print("名字不得為空") name = input("請輸入名字: ") print("Welcome, " + name) ``` ---- ## 範例 ```python= # for import time count = int(input("從多少開始倒數: ")) for i in range(count, -1, -1): print("倒數到: " + str(count)) time.sleep(1) print("倒數結束") ``` ---- ## 迴圈控制 - `break` - 直接中斷現在的**整個**迴圈 - `continue` - 跳過現在正在進行的**這一次**迴圈 ---- ## 範例 ```python= name = input("請輸入名字: ") while True: print("名字不得為空") name = input("請輸入名字: ") if name != "": break print("Welcome, " + name) ``` ---- ## 範例 - `range` 左閉右開 ```python= MAX = 0 for n in range(10): n = int(input("輸入 0 ~ 100 的數字: ")) if n > 100 or n < 0: print("範圍錯誤") continue MAX = max(MAX, n) print("最大值是 " + str(MAX)) ``` ---- ## 巢狀迴圈 ```python= for i in range(1, 10): for j in range(1, 10): print(f"{i}*{j}={i*j}", end=" ") print() ``` ---- ## Quiz 輸出 0 到 1 的每個小數,取到小數點後第二位 即,$0.00,0.01,0.02,...,0.99,1.00$ ---- ### Ans ```python= for i in range(0, 101): print("%.2f" % round(i / 100, 2)) ``` --- ## String 一大堆字連在一起 ---- ## 範例 ```python= s1 = "abc" s2 = 'abc' s3 = """abc 123""" ``` ---- ## 字串格式化 ```python= name = "siriuskoan" print("My name is {}".format(name)) print(f"My name is {name}") ``` ---- ## 字串操作 ```python= string = "I love cat" # 長度 print(len(string)) # 索引 print(string[2]) # 分割 print(string[2:6]) ``` ---- ## 字串處理函式 ```python= string = "I love dog" # replace print(string.replace("dog", "cat")) # find dog_index = string.find("dog") print(f"The word dog is at {dog_index} to {dog_index + 2}") # split data = "Shohei Ohtani,57,17,.298".split(",") print(f"Player: {data[0]} AB: {data[1]} \ H: {data[2]}, AVG: {data[3]}") ``` ---- ## 字串處理函式 (cont.) ```python= # join like = ["Reading", "Coding", "Gaming"] print("I like " + ", ".join(like)) # strip name = input("名字: ") # name is " siriuskoan " print(name.strip()) ``` --- ## `list` 可以裝好幾項資料的資料結構 ---- ## 範例 ```python= li = [1, 2, 3] for ele in li: print(ele) # or for i in range(len(li)): print(li[i]) ``` ---- ## 分割 ```python= li = [1, 2, 3, 4, 5, 6, 7, 8, 9] print(li[0:5]) print(li[:-1]) print(li[::-1]) ``` ---- ## 串列操作 ```python= li = [1, 2, 3, 4, 5] li.append(6) li.extend([7, 8]) li.insert(0, 0) print(li.index(3)) print(li.count(1)) li.pop() li.remove(0) li.clear() ``` ---- ## 串列操作 (cont.) ```python= li = [2, 3, 9, 7, 6, 0] print(list(reversed(li))) li.reverse() print(sorted(li)) li.sort() ``` ---- ## `list` 的指派 ```python= L1 = [1, 2, 3, 4, 5] L2 = L1 L2[0] = -1 print(L1, L2) # 相同 ``` vs. ```python= L1 = [1, 2, 3, 4, 5] L2 = L1.copy() # or L1[:] L2[0] = -1 print(L1, L2) # 只有 L2 被改掉 ``` ---- ## `enumerate` ```python= li = [1, 2, 3, 4, 5] for index, value in enumerate(li): print(f"Index {index} is {value}") ``` ---- ## `map`、`filter` ```python= li = [-2, 2, 3, -10, 8, -7, 1] li = list(map(abs, li)) ``` ```python= li = [-2, 2, 3, -10, 8, -7, 1] def check_larger_than_zero(n): return True if n > 0 else False li = list(filter(check_larger_than_zero, li)) ``` --- ## `dict` 字典 對鍵值對 (key-value pair) 做一對一的對應 key 必須要 immutable (不可變動) ---- ## 範例 ```python= d = {"name": "siriuskoan", "age": 19, "gender": "male"} print(d["name"]) # solve key error print(d.get("name")) # 更改值 d["name"] = "phkoan" # 新增 key d["department"] = "CS" # 刪除 key del d["gender"] ``` ---- ## `dict` 遍歷 ```python= d = {"name": "siriuskoan", "age": 19, "gender": "male"} for value in d.values(): print(value) for key in d.keys(): print(key) for k, v in d.items(): print(f"key {k} with value {v}") ``` ---- ## JSON ```python= import json json_data = """ {"name": "siriuskoan", "hobby": ["reading", "coding"]} """ d = json.loads(json_data) ``` --- ## Function 把一塊程式碼包起來,以利後續使用及功能區分 ---- ## 範例 ```python= def say_hello(name): print(f"Hello, {name}") def add(a, b, c = 0): return a + b + c ``` ---- ## Asterisks ```python= def add(*numbers): s = 0 for n in numbers: s += n return s def mapping(**kv): for k, v in kv.items(): print(f"{k}: {v}") ``` ---- ## Scope 會先從自己的 symbol table 找,找不到再去 global ```python= g = 10 def f(): print(g) g = 5 f() ``` ```python= g = 10 def f(): global g print(g) g = 5 f() ``` 建議變數用傳的,不要扯到一堆 global、local 的問題 ---- ## `lambda` 匿名函式 ```python= INPUT = "2139023, 3242, 34.2, 23, 43".split(", ") print(list(map(lambda x: int(x) ** 3 + 1, INPUT))) ``` ---- ## 遞迴 自己呼叫自己 注意終止條件及邊界處理 ```python= def fib(n): if n == 0 or n == 1: return 1 return fib(n - 1) + fib(n - 2) print(fib(10)) ``` --- ## Module 一整份 (可能是一個或多個 python 檔案) 可以讓你引用的程式 ---- ## `import` 引入 python 檔案或函式庫 ```python= import math print(math.sqrt(4)) import math as MATH print(MATH.sqrt(4)) from math import sqrt print(sqrt(4)) from math import sqrt as s print(s(4)) ``` ---- ## `import` 強烈建議不要用 `from module import *` 這種寫法 --- ## virtual environment 讓開發者可以針對不同專案獨立出不同開發環境的好幫手 ---- ## 使用 安裝 `virtualenv` 套件 ```bash $ pip install virtualenv ``` 建立新的虛擬環境 ```bash $ virtualenv venv ``` 進入虛擬環境 ```bash $ .\venv\Scripts\activate ``` 這時候應該會看到 prompt 前面多出 `(venv)` ---- ## 使用 進到去之後,就是一個完全與外部無關的環境了 接著可以開始安裝需要的套件等等

    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