Mes
    • 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
    • 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 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
    ###### tags: `Python` # While 與 For 迴圈 **<a href="https://hackmd.io/@Mes/python_note" class="redlink">點此回到 Python筆記 目錄</a>** # # 前言 在寫程式的時候,我們一定會遇到需要重複執行某條或某些指令的時候。這時候我們就需要利用循環結構。 Python中要建立循環結構有兩種方法,一種是 For 迴圈,另一種是 While 迴圈。 # For 迴圈 如果我們事先知道某件事情要做幾次,那我們可以使用 For 迴圈,舉個例子,我們現在要把 1~100 的數字全部加起來,因此「加法」這個動作就需要做100次: ```python= sum = 0 for number in range(1,101,1): sum += number print(sum) print(number) ``` 我們可以利用上例來知道 For 迴圈的語法,首先會有一個關鍵字 `for` , `for` 的後方會接一個變數,我這邊取叫 number ,變數的後方要有關鍵字 `in` , `in` 的後方要接一個容器(後面會講什麼是容器),或者是一個範圍,上例中接的是範圍,會有關鍵字 `range()`, `range()` 括號內會有三個數字,它們代表的意義由左至右分別為 「前方的變數要從多少開始」、「前方的變數如果將等於多少時要終止程式」、「前方的變數每執行一次迴圈後要加多少」,以上例來講,我們要從一加到一百,所以數字要從一開始,到一百的時候就結束(所以要填101),每次數字會加一,因此括號內填的是(1,101,1)。 For 迴圈後方記得也要有冒號,而冒號後會接一塊代碼塊,代碼塊的內容代表每執行一次迴圈要做什麼事情,以上例來說就是 `sum += number`。 另外 `range()` 的前後兩項有預設值,分別是 0 和 1,也就是說,如果我們「每次結束迴圈,變數都加一」,那我們第三格就可以省略不寫,同理,如果變數是從 0 開始算起,那我們也可以省略不寫。 但要注意一下順序,如果第三項並不是預設值,那第一項就不能省略。 我們再來看一個例子,假設我們要把 1~100 的偶數都加起來,那我們可以這樣做: ```python= sum = 0 for number in range(0,101,2): sum += number print(sum) print(number) ``` 當然我們也可以利用上一章學到的 If判斷句 來寫: ```python= sum = 0 for number in range(1,101): if(number%2 == 0): sum += number print(sum) print(number) ``` 那上下兩種寫法哪種比較好呢? 答案是上面那種,原因是因為下面的迴圈執行了 100 次,但上面的只有 50 次。 # While 迴圈 那如果我們不曉得需要循環幾次,我們可以使用 While迴圈,假設我們要寫一個猜數字的遊戲,電腦隨機出一個數字,而我們需要輸入數字,並且要根據我們輸入的值提供提示(太大了,太小了),如果玩家猜中了數字,電腦會告訴他猜中了,還有他猜了幾次: ```python= import random answer = random.randint ( 1 ,100 ) counter = 0 while (True) : counter += 1 number = int ( input ( '請輸入: ' )) if number < answer : print ( '大一點' ) elif number > answer : print ( '小一點') else : print ( '恭喜你猜對了!' ) break print ( "你總共猜了",counter,"次" ) ``` 在這邊我們引入了函式庫 `random` ,這個函式庫包含了許多用來模擬隨機的函式,因為我們現在電腦要隨機出一個數字,所以會用到這個函式庫。 在第三行我們可以看到有個函式 `random.randint(1,100)` 可以看見括號內傳了兩個數字進去,前者代表我們最小值,後者代表了最大值,這個函式的功能就是隨機出一個位於最小值與最大值內的數字,因此這行程式碼就會隨機產生一個 1~100 的數字,然後賦值給 `answer` 。 下方就是這小節的重點, While迴圈。 它會有一個關鍵字 `while` ,後面會接一個布林值或者一個可以回傳布琳值的判斷式,括號是可加可不加的,如果回傳 `true` 那程式便會進到迴圈,否則會跳過這個迴圈。 而上例迴圈中的最後還出現了一個新東西叫做 `break` ,這個迴圈的另一個關鍵字,它也可以用在 `for迴圈` ,它的用途跳出迴圈,當程式讀到 `break` 時便會從迴圈出來,繼續讀迴圈後的程式 # 巢狀迴圈 和 If 一樣, While 與 For 迴圈也可以有巢狀迴圈,也就是說可以在迴圈裡面再寫一個迴圈,例如我們要寫一個九九乘法表: ```python= for i in range(1,10): for j in range(1,10): print(f"{i*j:>4}",end="") print() ``` 註:上方的 end 代表這行印完後要再印什麼,因為 `python` 預設的 `print()` 包含了自動換行,為了讓它不要換行,我們需要在後方加上 `end=""` ,代表這行印完後什麼都不要做,然後再手動換行。 另外,不要忘記,無論是 `For` 還是 `While`,他們都是迴圈,因此是可以互通的,也就是說,用 `For`迴圈做得到的事,用 `While` 一定也可以做到,但差別就在好不好寫而已。 # 練習 ### 練習1:蓋出輸入層數的星星塔 > 輸入一個層數,並且蓋出相對層數的星星塔, ex: ```python= 輸入:5 輸出: * *** ***** ******* ********* ``` 參考解答: ```pyhton= n = int(input("> ")) for i in range(n): print( " "*(n-1-i) + "*"*(1+2*i) ) ``` ### 練習2:印出 1~100內 的質數 > 提示:質數的特性就是它只能被自己和1整除 參考解答: ```python= for number in range(1,101): is_prime = False for i in range(1,number): if(number%i == 0 and i != 1): break if(i == number-1): is_prime = True if(is_prime): print(number," 是質數") ``` ### 練習3:輸入數字,判斷是不是質數,輸入 -1 時才結束程式,並告訴使用者共輸入了幾次 > 提示:結合 While 與 For 迴圈 來做 ```python= counter = 0 while (True): n = int(input("> ")) counter += 1 is_prime = False if(n == -1): print("您總共輸入了", counter, "次") print("謝謝使用!") break for i in range(1,n): if(n%i == 0 and i != 1): print(n,"不是質數") break elif(i == n-1): is_prime = True if(is_prime): print(n,"是質數") ``` <style> .green { color:#29E5A9; } .brown { color:#990000; } .pink { color:#C18387; } .red { color:#E71B18 ; } .blue { color:#0b5394; } .purple { color:#AC9FDD; } @-webkit-keyframes A { 0% { color:#C10066;} 10% { color: #CC0000;} 20% { color: #E63F00; } 30% { color:#EE7700; } 40% { color: #DDAA00; } 50% { color:#EEEE00;} 60% { color: #99DD00;} 70% { color:#66DD00;} 80% { color: #00DDDD;} 90% { color: #0044BB;} 100% { color: #A500CC;} } #animation_title{ animation: A 3s ease 0s infinite alternate; -webkit-animation: A 3s ease 0s infinite alternate; } </style> <style> a.redlink { color:#DF2F6A; } a.redlink:link { color:#DF2F6A; text-decoration:none; } a.redlink:visiteid { color:#DF2F6A; text-decoration:none; } a.redlink:hover { color:#19CABC; text-decoration:none; } a.redlink:active { color:#000000; text-decoration:underline; background:#FFFFFF; } </style> <style type="text/css"> h1 { font-size:; color:#0b5394; } h2 { font-size:; color:#0b5394; } p { font-size:; color:; } h3 { font-size: ; color:#990000; } h4 { font-size:; color:#990000; } </style>

    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