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
    • 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
    # 4. 流程控制與迴圈 ###### 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) ::: # 一、流程控制 =>判斷式 ## 1. 判斷式種類 1. if 如果. . . 2. elif 不然如果. . . 3. else 不然. . . ## 2. 判斷式用法 - bool = 布林值 關於布林值請看第二篇資料型態說明 判斷式內要執行的 程式碼(code) 需要進行縮排,即,按鍵盤上的tab ```python= if bool: #做某些事情. . . elif bool: #做某些事情. . . else: #做某些事情. . . if bool and bool: #如果兩個bool都是True 做某些事情. . . if bool or bool: #如果兩個bool有一個是True 做某些事情. . . if not bool: # not 會反轉bool 即 如果bool為True 則被轉為False #如果bool是False 做某些事情. . . if var1 is var2: #如果變數var1的id 等於 var2的id 做某些事情. . . #兩個不同的變數 可能資料相同 但是 id(相當於記憶體位置) 卻不同 # var1 == var2 可以檢查 兩變數的 資料 是否一樣 # var1 is var2 則是檢查 兩變數是否 完全 一致 ``` ## 3. 實際使用例子 ```python= #取得使用者輸入 並轉為int整數 a = int(input()) #input()可以讓使用者在Terminal進行輸入 輸入的資料會以字串被儲存 #如果a成功轉為整數的話就進行判斷 => 因為可能使用者輸入英文字母或中文 就會出錯 if type(a)==int: #type() 可以取得變數的資料型態 if a >= 9: print("大於或等於9") #如果 a 大於 等於 9 => 輸出 "大於或等於9" elif a < 5: print("小於5") #不然如果 a 小於 5 => 輸出 "小於5" else: print("介於5~8之間") #不然 => 輸出 "介於5~8" 之間 else: print("請輸入數字") #如果使用者輸入字元 提示使用者必須輸入數字 ``` ## 4. 資料型態的True與False | False | True | |:-:|:-:| | False | True | | not True | not False | | 0 | 0以外的任何數 | |None|除了左邊列出的以外| |空字串 "" ''|任何資料或變數| |空列表 / 集合|都會被視為True| # 二、流程控制 =>迴圈 ## 1-1. 迴圈種類 / 結構 ### while 迴圈 ![](https://i.imgur.com/r3pxbSO.png) . ### for 迴圈 ![](https://i.imgur.com/5Iwhsnc.png) . ## 1-2. 常用配套語法 || 語法 | 作用 |適用於|例子| |:-:|:-:|:-:|:-:|:-:| |2.|range()|迴圈次數 / 數字範圍|for|例2 3 4| |1.|not|轉變布林值|while|例1| |3.|in|布林值 檢查物件是否在列表中|while|例2 3 4| |4.|try|嘗試|while / for|例3| |5.|except|當出現錯誤|while / for|例3| |6.|finally|最後|while / for|例3| |7.|else|不然 / 最後|while / for|例2 3| |8.|contiue|繼續|while / for|例1 3| |9.|break|退出迴圈|while / for|例1 3| . ### 1-3. 實際使用例子 1. 「當」 a < 10 的時候 a+1 如果 a 依然小於 10 繼續 直到 a < 10 為 False ```python= #先定義初始 a 值 a = 0 #第一種寫法 while a < 10: a+=1 # += 運算子 更多運算子可以回上一篇查看 #第二種寫法 while(1): a+=1 if not a < 10: # 如果 a 不小於 10 break #強制退出迴圈 else: #不然 continue #強制進入下一圈迴圈 print("owo") #因為 continue 強制進入下一圈迴圈 這個print() 永遠不會被執行 ``` 2. 「以」 變數 _ 儲存代表 列表c 裡的物件 然後印出 並在印出全部物件的最後印出 "end" ```python= #先定義 列表c 變數_是用來暫時儲存物件的 不需要事先定義 通常暫時變數會使用 _ 作為變數名稱 c = ["a", 1, 7, 10, "gg", "88", "omg", True, False] for _ in c: print(_) else: print("end") ``` 3. 不斷「嘗試」印出列表 c 中的物件 並附帶印出在其列表中的位置 並在最後印出"end" ```python= #先定義 列表c c = ["a", 1, 7, 10, "gg", "88", "omg", True, False] #第一種寫法 for _ in c: print(c, c.index(_)) #index詳細用法解釋可以回上一篇查看list語法 else: print("end") #第二種寫法 i = 0 #定義 i 變數為0 用來指定列表中的物件 while(1): try: #嘗試印出 c 的第 i 個物件 print(c[i], i) #輸出 c[i] 然後空格 再輸出 i => ,會等於一個空格 except: #當出現錯誤 => i 大於 列表c 的長度 break # 強制退出迴圈 finally: #不管上面嘗試成不成功 都會執行 即使強制結束迴圈 也會執行最後一次才退出 i+=1 #每次迴圈 i 都增加 1 continue #繼續下一圈迴圈 else: print("end") ``` 4. 讓使用者輸入兩個數字x y 以空格分隔 並計算 x 整數加到 y 的值 ```python= # input() 取得使用者輸入 # split() 以空格作為分割點 將字串 (在此為使用者輸入) 分割為列表 # 變數1 , 變數2 = 列表 => 列表長度要等於左邊變數的數量 # 變數1 會儲存 列表第一個物件 也就是列表0號位置的物件 # 變數2 會儲存 列表第二個物件 也就是列表1號位置的物件 # 將 分割後的 使用者輸入列表 內的物件 一一提取 並轉為int整數 放進[]裡變成列表 #第一種寫法 x, y = [int(_) for _ in input().split()] Sum = 0 # 把 x 到 y 的數字一一提取出來 存到變數 _ 中 (因為 range(a, b) 只會跑 a 到 b-1 所以要+1 for _ in range(x, y+1): Sum += _ # += 運算子詳細解釋可以回上一篇查看 print(Sum) # 印出結果 #進階寫法 x, y = [int(_) for _ in input().split()] #看上面解釋 # 將 x 到 y 的所有數字以 range(x,y) 生成並存到[]列表中 再使用sum函數加總列表中的所有數字 print(sum([int(_) for _ in range(x, y)])) ``` ### [上一篇](https://hackmd.io/UGzZn3f6Sge-HI1EVx6MWg?view) ### [下一篇](https://hackmd.io/sZPWfF2RSsaQb03i-gVMpQ?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