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
      • Invitee
    • 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
    • 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 Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync 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
Invitee
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: `Python` # If Else 判斷句 與 函式庫簡介 **<a href="https://hackmd.io/@Mes/python_note" class="redlink">點此回到 Python筆記 目錄</a>** # 前言 到目前為止,我們的程式都是一行一行全部讀下來執行的,這種程式結構我們稱它為順序結構。 然而只有順序結構並不夠,有些狀況是順序結構無法完成的,舉個例子,我們寫了一個遊戲,遊戲中玩家會來到兩扇門前,如果玩家選擇了左邊的門,便會傳送到A點,如果選擇了右邊的門,便會傳送到B點。 這種狀況就無法用順序結構完成,因為進了A點,玩家就不會進到B點,反之亦然。 當然,設計上面也不能讓他兩個都選,此時就需要分支結構了。 ![](https://i.imgur.com/7jGNnxT.jpg) # If 語法 在 Python 中要建構分支結構,可以使用 `if`、`elif` 和 `else` 關鍵字,下面我們來給個例子: ```python= print("你來到了門前,有兩扇門,如果你想進入左邊的門,請輸入1,如果想進入右邊的門,請輸入2") n = int(input("> ")) s = "初始位置" if(n == 1): print("你進入了左邊的門,將把你傳送至A點") s = "A點" elif(n == 2): print("你進入了右邊的門,將把你傳送至B點") s = "B點" else: print("無效的輸入,請輸入 1 或 2") print("你現在位於" + s) ``` 這邊用了一個新的函式,叫做 `input()` ,當程式執行到這個函式時,會要求使用者輸入一個值,並回傳輸入的值,後方括號內要填入「要求使用者輸入時,要印出什麼東西」。 回傳值的型態預設是 String ,但這個程式內我希望它輸入的是一個整數 int ,因此我們可以使用強轉函式 `int()` 來將字串轉為整數,再使用 賦值運算符 `=` 來將回傳的值丟給「變數n」。 `if`、`elif` 和 `else` 等關鍵字的後方需要有「冒號」來表示一個代碼塊的開頭,像是上例中, `if(n == 1):` 下方的 `print("你進入了左邊的門,將把你傳送至A點")` 與 `s = "A點"` 就是一個代碼塊。 與C/C++、JAVA等語言不同,Python不使用大括號,而是使用縮進的方式來構造代碼塊,上方這個例子內,在 `if(n == 1):` 下方的 `print("你進入了左邊的門,將把你傳送至A點")` 與 `s = "A點"` ,前方都有四格空白(一個tab),而到了 `elif(n == 2):` 這行時前方並沒有空格,因此上方這兩行便形成了一個構造代碼塊。 在 `if(n == 1):` 內, `n == 1` 是判斷式,它會回傳一個布林值,如果回傳的是true,程式便會執行它下方的代碼塊,如果是false,則跳過下方的代碼塊,檢查下一個條件 (n == 2) , 而 `else` 的後方並沒有判斷式, `else` 的作用是 「當前面的條件全部不符合時,便會進到 else 後方的代碼塊」 # 函式庫簡介 那假設今天的條件變複雜了,假如你進入了左邊的門,而你的職業是戰士,那你便會被傳送到A點,而如果你的職業是法師,那便會被傳送到B點。 但如果你選了右邊的門,而你的職業是戰士,那你會被傳送到C點,而如果你的職業是法師,便會傳送到D點。 文字敘述看起來很複雜,讓我們畫個表格來看: | 選擇的門 | 職業 | 被傳送到的地點 | | -------- | ---- | -------------- | | 左邊的門 | 戰士 | A點 | | 左邊的門 | 法師 | B點 | | 右邊的門 | 戰士 | C點 | | 右邊的門 | 法師 | D點 | 這樣就清楚多了! 那我們的程式該怎麼寫呢? 我們可以列舉: ```python= import sys print("你來到了門前,有兩扇門,如果你想進入左邊的門,請輸入1,如果想進入右邊的門,請輸入2") n = int(input("> ")) if(n != 1 and n != 2): sys.exit("無效的輸入,請輸入 1 或 2") print("請問您的職業是戰士還是法師? 如果是戰士,請輸入1,如果是法師,請輸入2") role = int(input("> ")) if(role != 1 and role != 2): sys.exit("無效的輸入,請輸入 1 或 2") s = "初始位置" if(n == 1 and role == 1): print("您將被傳送至A點") s = "A點" elif(n == 1 and role == 2): print("您將被傳送至B點") s = "B點" elif(n == 2 and role == 1): print("您將被傳送至C點") s = "C點" elif(n == 2 and role == 2): print("您將被傳送至D點") s = "D點" print("你現在位於" + s) ``` 這邊我們又看見了新東西 `import sys` , 至今為止我們都只利用了最基本的函式,像是 `input()`、`print()` 之類的,然而,當我們需要用到一些比較特別的函式時,我們需要去尋找它的函式庫名稱,並於一開始寫下 `import 函式庫名稱` 。 那什麼是函式庫呢? 我們之前提過,`input()`和`print()`這類的東西叫做函式,括號內通常會填入一些參數,然後這段程式便會利用我們填入的東西去做一些事情,像是`print()`便會把我們填入的東西給印出來。 那在一開始我們講說可以把它當成一個語法,那麼函式庫就是一個倉庫,裡面裝了很多別人已經幫妳寫好的語法(函式),當你需要用到這個語法(函式)的時候,我們便要告訴系統,這個函式要從這個倉庫裡去找,因此我們才需要`import 函式庫名稱`。 那麼上方這個例子中的 `sys.exit()` 的作用就是印出括號內填入的字串,並結束程式。 可以看見 `sys` 的後面有一個點,這個就代表我們接下來要用的函式要去 `sys` 這個倉庫(函式庫)裡面找,而後方的 `exit()`便是我們要使用的語法(函式)。 那關於這部分後面的課還會有更詳細的講解,這邊只是先稍微提個概念而已。 # 巢狀if 在上方那個例子內我們列舉出了所有的狀況,然而它並不好閱讀,這時我們可以使用「巢狀if」。 `if`、`elif` 和 `else` 關鍵字後方的代碼塊內也能再寫一次 If Else 判斷式,這種狀況我們就稱它為 巢狀if: ```python= print("你來到了門前,有兩扇門,如果你想進入左邊的門,請輸入1,如果想進入右邊的門,請輸入2") n = int(input("> ")) place = "初始位置" role = 0 if(n == 1): print("請問您的職業是戰士還是法師? 如果是戰士,請輸入1,如果是法師,請輸入2") role = int(input("> ")) if(role == 1): print("您將被傳送至A點") place = "A點" elif(role == 2): print("您將被傳送至B點") place = "B點" else: print("無效的輸入,請輸入 1 或 2") elif(n == 2): print("請問您的職業是戰士還是法師? 如果是戰士,請輸入1,如果是法師,請輸入2") role = int(input("> ")) if(role == 1): print("您將被傳送至C點") place = "c點" elif(role == 2): print("您將被傳送至D點") place = "D點" else: print("無效的輸入,請輸入 1 或 2") else: print("無效的輸入,請輸入 1 或 2") print("經過了傳送,你現在位於" + place) ``` 這樣就好閱讀多了! # 練習 ### 練習1:百分製成績轉換為等級製成績。 > 要求:如果輸入的成績在90分以上(含90分)輸出A;80分-90分(不含90分)輸出B;70分-80分(不含80分)輸出C;60分-70分(不含70分)輸出D;60分以下輸出E。 參考解答: ```python= score = float ( input ( '請輸入成績: ' )) if score >= 90 : grade = 'A' elif score >= 80 : grade = 'B' elif score >= 70 : grade = 'C' elif score >= 60 : grade = 'D' else : grade = 'E' print ('對應的等級是:' , grade ) ``` <br> ### 練習2:輸入三條邊長,如果能構成三角形就計算周長和面積。 ```python= a = float ( input ( 'a = ' )) b = float ( input ( 'b = ' )) c = float ( input ( 'c = ' )) if a + b > c and a + c > b and b + c > a : print ( '周長: %f' % ( a + b + c )) p = ( a + b + c ) / 2 area = ( p * ( p - a ) * ( p - b ) * ( p - c )) ** 0.5 print ( '面積: %f' % ( area )) else : print ( '不能構成三角形' ) ``` <br> ### 練習3:判斷小明能不能結婚 > 我國民法在民國100年以前,規定男女結婚最低限度的年齡則分別為 18 歲及 16 歲。 要求:輸入小明的性別和年齡,判斷它可不可以結婚,性別可以像前面一樣用 1 和 2 來表示。 參考解答: ```python= print("請輸入生理性別,如果是男性則輸入 1 ,女性則輸入 2") sex = int(input("> ")) print("請輸入年齡") age = int(input("> ")) if( sex == 1 ): if( age >= 18 ): print("小明可以結婚") else: print("小明不能結婚") elif( sex==2 ): if( age >= 16 ): print("小明可以結婚") else: print("小明不能結婚") else: print("無效的輸入") ``` 註:此題取自 [巢狀 if | C++與演算法](https://www.csie.ntu.edu.tw/~b98902112/cpp_and_algo/cpp/nested_if.html) # 額外文章 如果你的 If Else 判斷句的結構很簡單,那可能就可以用三元運算子簡寫它: **<a href="https://iter01.com/114859.html" class="redlink">python 的三元運算子</a>** <br> 如果你是學過其他語言的朋友,在學Python的時候可能會對它的全域變數與區域變數感到疑惑,那你可以看看這篇文章: **<a href="https://sites.google.com/site/ezpythoncolorcourse/globalandlocalvariable" class="redlink">全域變數和區域變數</a>** <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