鄧鄧人豪
    • 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
    --- type: slide tags: Sprout2023-Presentation title: Python if - 資訊之芽 2023 python 語法班 --- # Python if 資訊之芽 Python 語法班 2023/03/12 鄧人豪 --- ## 課程大綱 Outline ---- 1. 課程回顧 2. 比較運算子 3. 邏輯運算子 4. if 基本語法 5. 補充 --- ## 課程回顧 Recap ---- ### 輸出 ```python= print("Hello World") ``` ---- ### 變數 ```python= aInteger = 100 aFloat = 123.456 aString = "Hello World" aBool = True print(type(aInteger)) # <class 'int'> print(type(aFloat)) # <class 'float'> print(type(aString)) # <class 'str'> print(type(aBool)) # <class 'bool'> ``` ---- ### 輸入 ```python= number = int(input("請輸入一個數字")) print(number) ``` ---- ### 運算子 ```python= x = 9 y = 3 print(x + y) # 12 print(x - y) # 6 print(x * y) # 27 print(x / y) # 3.0 ``` --- ## 比較運算子 Comparison Operators ---- ### 比較運算子 - `<`, `>`: 小於, 大於 - `<=`, `>=`: 小於等於, 大於等於 - `==`, `!=`: 等於, 不等於 ---- ### 範例 ```python= print(2 < 1) # False print(2 > 1) # True print(2 <= 1) # False print(2 >= 1) # True print(2 == 1) # False print(2 != 1) # True print(1 == 1) # True print(1 <= 1) # True print(1 >= 1) # True ``` ---- ### 注意!!! #### `=` 與 `==` 不一樣喔 - `=` 用來 **指定** 變數的值 - `==` 用來 **比較** 是否相等 ---- ### `=` 與 `==` 不一樣 ```python= x = 2 y = 3 print(x == y) # False print(x = y) # 3 print(x) # 3 print(y) # 3 ``` ---- ### 那這樣呢? ```python= x = 2 y = 3 bool1 = x == y bool2 = x = y print(bool1) # False print(bool2) # 3 print(x) # 3 print(y) # 3 ``` ---- ### 比較規則 Comparison Rule ---- - 相同的型態才能比較 (`==`與`!=`例外) - 數字排序:依照大小 - 字串排序:從左到右一位一位進行比較 ---- ### 舉個例子 ```python= print(20 == "20") # False print(20 >= "20") # TypeError ``` ```python= print("abc" > "abd") # False print("22" > "111") # True ``` ---- ### Questions? --- ## 邏輯運算子 Logical Operators ---- ### 邏輯運算子 - True: 真, False: 假 - A `and` B: A 且 B - A, B 都為 True,「A and B」才為 True - A, B 只要有一個為 False,「A and B」就為 False - A `or` B: A 或 B - A, B 只要其中一個為 True,「A or B」就為 True - A, B 都為 False,則「A or B」才為 False - `not` A: 非 A - True 變 False、False 變 True ---- ### 真值表 Truth Table | A | B | A and B | A or B | not A | | ----- | ----- | ------- | ------ | ----- | | True | True | True | True | False | | True | False | False | True | False | | False | True | False | True | True | | False | False | False | False | True | ---- ### 範例 ```python= print(2 > 1 and 3 > 2) # True print(1 > 2 and 3 > 2) # False print(1 > 2 or 3 > 2) # True print(1 > 2 or 2 > 3) # False ``` ---- ### 進階範例 ```python= print(not True and False or True or False) # True print(not((True and False) or (True or False))) # False ``` [Operator Precedence:](https://docs.python.org/3/reference/expressions.html#operator-precedence) not > and > or ---- ### Questions? --- ## if-else 基本語法 ---- ### 情境 - 如果年紀小於等於 8 歲,則遊樂園入場費打 1 折 - 如果年紀小於等於 12 歲,則只需要一半的入場費 - 如果年紀大於等於 65 歲,則入場費打 8 折 - 如果都不符合則是全票 ---- ```python= fee = 1000 age = int(input("請輸入你的年紀")) if age <= 8: # 如果年紀小於等於 8 歲 fee = fee * 0.1 # 遊樂園入場費打 1 折 print(fee) ``` 注意:冒號與縮排(後面說明) ---- ### 這樣正確嗎? ```python= fee = 1000 age = int(input("請輸入你的年紀")) if age <= 8: # 如果年紀小於等於 8 歲 fee = fee * 0.1 # 遊樂園入場費打 1 折 if age <= 12: # 如果年紀小於等於 12 歲 fee = fee * 0.5 #只需要一半的入場費 print(fee) ``` ---- ### 解決辦法:使用 if-elif-else ```python= fee = 1000 age = int(input("請輸入你的年紀")) if age <= 8: # 如果年紀小於等於 8 歲 fee = fee * 0.1 # 遊樂園入場費打 1 折 elif age <= 12: # 如果年紀小於等於 12 歲 fee = fee * 0.5 # 只需要一半的入場費 elif age >= 65: # 如果年紀大於等於 65 歲 fee = fee * 0.8 # 入場費打 8 折 else: # 如果都不符合則是全票 print("乖乖買全票吧~") print(fee) ``` ---- ### 條件句重點整理 1. 一定會是 if 開頭,其他 (elif, else) 都是非必要的 2. 上一個條件不符合時,如果要繼續判斷下一個條件,則用 elif 3. 如果前面全部的條件都不符合的時候,用 else 4. 一個條件句中的數量: - if: 必定只有一個在開頭 - elif: 可以有 0 個或很多個,而且在 if 的後面、else 的前面 - else: 可有可無,但最多只會有一個,而且一定是在條件句的最後 ---- ### 再來一個範例 ```python= score = int(input("請輸入你的成績")) if score >= 90: print("你獲得了 A+") elif score >= 85: print("你獲得了 A") elif score >= 80: print("你獲得了 A-") elif score >= 60: print("你至少及格了~") else: print("你被當了(´・ω・`)") ``` ---- ### 覺得混亂就畫流程圖看看吧~ ![](https://i.imgur.com/iBQpxrK.jpg) Note: https://drive.google.com/drive/folders/1eW1YUmnGgn1_kCZW23e04Pk2isBYubM5 ---- ### Questions? --- ## 縮排 Indentation - 縮排就是程式前面的幾個空白 - 通常用 1 個 Tab 或 4 個 Space - Python 以冒號「:」與縮排來表示程式區塊 - 同個區塊內的空白數都要相同 ---- ### 錯誤範例 ```python= if 10 > 5: print("原來 10 大於 5 啊") # IndentationError 缺少縮排 print("End") ``` ```python= if 10 > 5: print("原來 10 大於 5 啊") print("End") # IndentationError 縮排的空白數不同 ``` ```python= if 10 > 5 # SyntaxError 缺少冒號 print("原來 10 大於 5 啊") print("End") ``` ---- ### 正確範例 ```python= if 10 > 5: print("原來 10 大於 5 啊") print("End") ``` ---- ### 區塊範圍 同樣的縮排空白數代表在同個區塊中 範例1: ```python= if 5 > 10: print("原來 5 大於 10 啊") print("End") ``` VS ```python= if 5 > 10: print("原來 5 大於 10 啊") print("End") ``` ---- 範例2: ```python= age = int(input("請輸入你的年紀")) if age >= 18: print("你成年了") if age >= 65: print("你也老了...") else: print("你還沒成年") ``` VS ```python= age = int(input("請輸入你的年紀")) if age >= 18: print("你成年了") if age >= 65: print("你也老了...") else: print("你還沒老") ``` ---- ### 注意!區塊內不可以是空的喔 錯誤範例 ```python= if 10 > 5: # 註解也不算程式碼喔 ``` - 解決辦法:用 pass - pass 不會做任何事,但可以讓空的區塊不會出現 error ```python= if 10 > 5: # 註解也不算程式碼喔 pass ``` ---- ### 快樂的練習時間 ( ̄▽ ̄)~* [neoj 3010 野豬騎士來囉](https://neoj.sprout.tw/problem/3010/) ---- ### 巢狀 Nested if ```python= a, b, c = 1, 2, 3 if c > b: if c > a: print("c is the biggest number") ``` ```python= a, b, c, d = 1, 2, 3, 4 if d > c: if d > b: if d > a: print("d is the biggest number") ``` ---- ### 但拜託別這樣做 (。﹏。*) ![](https://i.imgur.com/avDXmv8.png) ---- ### 請善用邏輯運算子 ```python= a, b, c, d = 1, 2, 3, 4 if d > c and d > b and d > a: print("d is the biggest number") ``` ---- ### 但如果條件很多怎麼辦? ```python= a = 13 if a == 2 or a == 3 or a == 5 or a == 7 or a == 11 or a == 13 or a == 17 or a == 19 or a == 23 or a == 29: print("a 是 30 以內的質數") else: print("a 不是 30 以內的質數") ``` ---- ### 請用 `\` 換行 `\` 後必須直接換行,不可以有任何空白 ```python= a = 13 if a == 2 or a == 3 or a == 5 or \ a == 7 or a == 11 or a == 13 or \ a == 17 or a == 19 or a == 23 or \ a == 29: print("a 是 30 以內的質數") else: print("a 不是 30 以內的質數") ``` ---- ### Questions? ---- ### 又是快樂的練習時間 (๑•̀ㅂ•́)و✧ [neoj 3011 三元排序](https://neoj.sprout.tw/problem/3011/) --- ## 補充 ---- ### 稍長的程式碼 ```python= condition = False a = 0 if condition: a = 1 else: a = -1 print(a) ``` ---- ### 三元運算子 Ternary Operator ```python= condition = False a = 1 if condition else -1 print(a) ``` ---- ### 真值測試 Truth Value Testing ---- ### False ```python= # Constants defined to be false print(bool(False), bool(None)) # Zero of any numeric type print(bool(0), bool(0.0)) # Empty sequences and collections print(bool(''), bool(""), bool(()), bool([]), bool({})) ``` ### 其他的都是 True ```python= print(bool(True), bool(3), bool('abc')) ``` [Truth Value Testing](https://docs.python.org/3/library/stdtypes.html#truth-value-testing) ---- 範例 ```python= a, b = 0, 3 if a: print(a) # 不會 print 0,因為 bool(0) 等於 False if b: print(b) # 會 print 3,因為 bool(3) 等於 True ``` ---- ### Questions? ---- ### 寫作業囉 ✧(≖ ◡ ≖✿) [neoj 3401 超級貓貓星際漫遊-1](https://neoj.sprout.tw/problem/3401/) [neoj 3402 超級貓貓星際漫遊-2](https://neoj.sprout.tw/problem/3402/) --- # Thanks!

    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