Fenrir Eclair
    • 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
    # 条件分岐(if、else、elif) ###### tags: `Python-老師` ## 条件分岐(Bunki)とは? プログラムは記述(Kijutsu)した順に実行されていきます。ただある条件によって処理を分けたい場合もあります。 「条件を満(mi)たしているかどうかで、やることを変えてね!」な命令が「条件分岐処理(ジョウケンブンキショリ)」です。 :::info *條件判斷* *程式雖會照著撰寫的順序執行,但亦會有希望程式依照條件執行的情況。* *「要依照條件式是否成立,而改變做的事情喔!」等的命令, 稱為「條件判斷處理」* ::: ## if if は指定した条件式が真の時にだけ処理を実行します。 :::info *if 只有在當指定的條件式為真時執行處理。* ::: ``` if 条件式: 条件式がTrueの時に実行する文 ``` ![](https://i.imgur.com/q7OSZmc.png) **Example:** 輸入分數,並印出,如果分數不到60顯示"Fail grades"。 ```python= grades = int(input("Input Grades: ")) if(grades < 60): print("Fail grades") print("Grades:", grades) ``` **Results:** ``` >>>Input Grades: 70 Grades: 70 >>>Input Grades: 59 Fail grades Grades: 59 ``` ## インデント - 縮排(indentation) インデントとは、行頭に空白を入れて文字を入れて字下げを行う事を言います。 pythonにおけるインデントは非常に重要です。なぜなら、pythonは同じ数の空白でインデントされたまとまりを一つのブロックと認識する為です。 Pythonのインデントには通常、4個の空白文字を使用します。(tab key) :::info *縮排,指的是在行的開頭插入空白使文字後退* *在Python縮排是非常重要的。因為Python會將使用同數目的空白所進行縮排的程式碼,視為一個區塊。* ::: ![](https://i.imgur.com/76fQ4K1.png) ## if else 条件式のTrueとFalseで、処理を分けたい場合、ifとelseを組み合わせて行い ます。条件式が成り立たない場合のみ、elseブロックの処理が実行されます。 :::info *若想用True和False來區分處理,則結合if和else來使用。唯有在條件式不成立時,else區塊的處理才會被執行。* ::: ``` if 条件式: 条件式がTrueの時に実行する文 else: 条件式がFalseの時に実行する文 ``` ![](https://i.imgur.com/ghbekkC.png) **Example2:** 判斷輸入是否為 0 ```python= number = int(input('Enter a number: ')) if number == 0: print(number,'is 0') else: print(number,'not 0') ``` **Results2:** ``` Enter a number: 10 0 is 0 Enter a number: 13 10 not 0 ``` **Example3:** 判斷輸入的成績是否及格 ```python= score = int(input('Enter a score: ')) if score >= 60: print(score,':PASS') else: print(score,':FAIL') ``` **Results3:** ``` Enter a score: 26 26 :FAIL Enter a score: 90 90 :PASS ``` ## ifのネスト if文の中にif文を入れ子にして、条件分岐を多段にできます。 :::info *if 的巢狀* *在if文之中,放入if文使之成為巢狀,可讓條件判斷成為多層判斷。* ::: ``` if 条件式1: 条件式1が真の時に実行する文 ... else: if 条件式2: 条件式1が偽で条件式2が真の時に実行する文 ... else: if 条件式3: 条件式1及び条件式2が偽で条件式3が真の時に実行する文 ... else: すべての条件式が偽のときに実行する文 ... ``` **Question:** 將輸入成績區分為 A(100 ~ 90), B(89 ~ 80), C(79 ~ 70), D(69 ~ 60) 和 F(59 ~ 0) 等 5 個等級。 **Results4:** ``` score: 90 Grade is: A score: 40 Grade is: F ``` **Example4-1:** ```python= score = int(input("score: ")) if score >= 90: print('Grade is: A') else: if score >= 80: print('Grade is: B') else: if score >= 70: print('Grade is: C') else: if score >= 60: print('Grade is: D') else: print('Grade is: F') ``` ネストにするとインデントが増えて見づらくなります。elifや論理演算を使った方がすっきりするでしょう。 :::info *如果寫成巢狀則縮排會增加,反而變得看不清楚。這時使用elif、邏輯運算子會使code比較清楚。 ::: ## elif if文の条件には引っかからなかったけど、別の条件に当てはまったらelseとは別の処理がしたい。といったときはどうするのでしょうか。これはelifで実現できます。 :::info *如果沒有滿足if文的條件,卻又想要其他條件成立並做出與else不同的處理,這時該怎麼辦呢?* ::: ``` if 条件式1: 条件式1がTrueの時に実行する文 ... elif 条件式2: 条件式1がFalseで条件式2がTrueの時に実行する文 ... elif 条件式3: 条件式1及び条件式2がFalseで条件式3がTrueの時に実行する文 ... else: すべての条件式がFalseのときに実行する文 ... ``` ![](https://i.imgur.com/ZDlVOYg.png) **Example4-2:** ```python= score = int(input("score: ")) if score >= 90: print('Grade is: A') elif score >= 80: print('Grade is: B') elif score >= 70: print('Grade is: C') elif score >= 60: print('Grade is: D') else: print('Grade is: F') ``` ![](https://i.imgur.com/DnUnYcv.png) --- ## Exercise ### Exercise - 1 次の要求を満たすプログラムを作成してください。 1. 数字を1つ入力することが出来る 2. 入力した数字が奇数(きすう)であれば「Odd number」と出力する 3. 入力した数字が偶数(ぐうすう)であれば「Even number」と出力する :::info *請做出滿足以下要求的程式* *1.可輸入一個數字* *2.若輸入的數字為奇數則輸出「Odd number」* *3.若輸入的數字為偶數則輸出「Even number」* ::: ![](https://i.imgur.com/qKZfhQj.png) **Code Example:** ```python= x = int(input()) if x % 2 == 0 : print("{} is an Even number.".format(x)) else : print("{} is an Odd number.".format(x)) ``` ### Exercise - 2 ユーザーに数字(西暦)を入力させ、閏年(じゅんねん)であるかを判断することが出来るプログラムを作成してください。判断基準は以下の通り: 1. 数字が4の倍数であればその年は閏年「leap year」と表示 2. 但し数字が100の倍数であれば2.よりも優先されその年は平年「Normal year」と表示 3. 更に数字が400の倍数であれば3.よりも優先されその年は閏年「leap year」と表示 :::info *請製作出一個程式,讓使用者輸入一個數字(西曆)後,判斷是否為閏年。其判斷基準為下:* *1.數字若為4的倍數則那一年為閏年並輸出「leap year」* *2.但數字若為100的倍數,則為平年並輸入「Normal year」* *3.而數字若為400的倍數則為閏年並輸出「leap year」* ::: ![](https://i.imgur.com/gxI4hgS.png) **Code Example(if else):** ```python= year = int(input('Please input year:')) if(year % 400 == 0): print('{} is a leap year.'.format(year)) else: if(year % 100 == 0): print('{} is a normal year.'.format(year)) else: if(year % 4 == 0): print('{} is a leap year.'.format(year)) else: print('{} is a normal year.'.format(year)) ``` **Code Example(elif):** ```python= if( year % 400 == 0): print('{} is a leap year.'.format(year)) elif( year % 100 == 0): print('{} is a normal year.'.format(year)) elif( year % 4 == 0): print('{} is a leap year.'.format(year)) else: print('{} is a normal year.'.format(year)) ``` **Code Example(and or):** ```python= y = int(input()) if y % 4 ==0 and y % 100 != 0 or y % 400 == 0: print("{} is a leap year.".format(y)) else : print("{} is not a leap year.".format(y)) ``` --- ### 方 if ```python= g = int(input()) if g >= 60: print("Good") else: print("Fail grades") print("garades = {} ".format(g)) ``` ```python= s = int(input("你的成績:")) if s >=90 : print("A") elif s>=80: print("B") elif s>=70: print("C") elif s>=60: print("D") else: print("F") print("garades = {} ".format(s)) ``` ```python= s = int(input("你的年齡:")) if s >=65 : print("恭喜你!可以退休了!") elif s>=20: print("恭喜你!成年了!") else: print("恭喜你!還很年輕!") print("你的年齡: {}歲 ".format(s)) ``` ```python= s = int(input("請輸入數字:")) if s%2==0: print("偶數") else: print("奇數") ``` ### 塗 ```python= #判斷奇數偶數 A = int(input("數字:")) if A % 2 == 0: print("{}是偶數喔".format(A)) else: print("{}是奇數喔".format(A)) ``` if else if else ... ```python= score = int(input("分數: ")) if score >= 90: print("評分:優") elif score >= 80: print("評分:良") elif score >= 70: print("評分:可") elif score >= 60: print("評分:普") else : print("評分:你被當了") ``` ### 劉 ```python= print("enter your grade") g=int(input()) if g <60: print("your grade is {}".format(g)) print("Failed") else : print("your grade is {}".format(g)) print("Passed") ``` if else if else ... ```python= print("enter your grade") g=int(input()) if g <60: print("your grade is {}".format(g)) print("Failed") print("your rank is F") else : print("your grade is {}".format(g)) print("Passed") if g<70: print("your rank is D") else : if g<80: print("your rank is C") else: if g<90: print("your rank is B") else : print("your rank is A") #elif print("enter your grade") g=int(input()) if g <60: print("your grade is {}".format(g)) print("Failed") print("your rank is F") else : print("your grade is {}".format(g)) print("Passed") if g<70: print("your rank is D") elif g<80: print("your rank is C") elif g<90: print("your rank is B") else: print("your rank is A") #exercise number = int(input()) if number%2 ==1: print("the numer you entered is Odd number") else : print("the number you entered is Even number") ``` ### 邱 ```python= g = int(input()) if g<60: print("fail grades") else: print ("pass") print("grades={} ".format(g)) ``` if else if else ... ```python= score = int(input("偏差值: ")) if score >= 90: print('level: A / 東大京大合格') elif score >= 80: print('Level: B / 東大京大合格') elif score >= 70: print('Level: C / 東大京大合格') elif score >= 60: print('Level: D / 早慶') else: print('Level: F / MARCH') score = int(input("偏差值: ")) if score >= 90: print('level: A / 東大京大合格') elif score >= 80: print('Level: B / 東大京大合格') elif score >= 70: print('Level: C / 東大京大合格') elif score >= 60: print('Level: D / 早慶') else: print('Level: F / MARCH') x=int(input()) if x%2==0: print("{} is an Even number.".format(x)) else: print("{} is an Odd number.".format(x))

    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