中興大學資訊社
      • 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
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners 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
    • 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 Help
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
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners 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
    --- title: 函式 - Python 教學 description: 中興大學資訊研究社1101學期程式分享會主題社課 tags: Python --- #### meet.google.com/czn-pbav-zvr ### md.nchuit.cc/py/ # 函式(Function) > [name=ZJ][time= 110,10,18] --- ## 函式是什麼? function 是一個建構程式的小區塊, 它就像是一台機器,你可以自行指定它的==功能==,以及所需要的原料(==輸入==)、產出(==輸出==)。 如此一來,在需要用到同一個操作的時候,只需要呼叫這個函式,就可以免去把同樣的程式碼不斷複製貼上的情況。 ---- ## 優點 1. 程式的重複利用性 2. 程式的易讀性 3. 程式的易除錯性 4. 程式的一致性 5. 程式的模組化 --- # 函式建立+呼叫 ## 建立函式 使用**關鍵字**==def==定義函式: 和 ==if==、==elif== 一樣,要在後面加==冒號==然後==縮排== ```python= def my_function(): print("My first function") #實際上"print()"就是一個函式 ``` ---- ## 呼叫函式 ```python= def my_function(): print("My first function") my_function() ###呼叫 ``` ### Result: My first function --- # 函式(Function)參數 ---- ## 引數、參數(Arguments, Parameters) 資料可以作為引數傳遞到一个函式中作為參數使用。 #### ex1: ```python= def f1(val): #建立函式 print(val) k=19 f1(k) #呼叫函式 ``` val 參數; k 引數 --- #### ex2: ```python= def f1(val): #建立函式 print("小"+val) f1("明") #呼叫函式 f1("夫") #呼叫函式 f1("聰") #呼叫函式 ``` val 參數; k 引數 ---- #### Result: 小明 小夫 小聰 --- ## 關鍵字參數(Keyword Argument)和 預設值參數(Default Argument) ---- ## 關鍵字參數(Keyword Argument) ```python= def f1(person, item): #建立函式 print(person +" uses "+item+ ".") f1(person="Ken", item="pen") #呼叫函式 f1("Ken", "pen") #呼叫函式 ``` ### Result: Ken uses pen. Ken uses pen. ---- ## 預設值參數(Default Argument) ```python= def f1(person, item, date="2022.10.18"): #建立函式 print(person ," uses ",item," on ",date,".") f1(person="Ken", item="pen") #呼叫函式 f1("Ken", "pen") #呼叫函式 ``` ### Result: Ken uses pen on 2022.10.18 . Ken uses pen on 2022.10.18 . --- ## 函式(Function) *args、**kwargs運算子 ---- ### 打包成tuple(*args) *Python會將參數資料打包成元組(Tuple)資料型態,那如果想打包成字典(Dictionary)資料型態,則可以使用 ** 符號 ```python= def f1(*data): #建立函式 print(data) f1("Ken","pen","2022.10.18") #呼叫函式 ``` #### Result: ('Ken', 'pen', '2022.10.18') ---- ### 打包成dictionary(**kwargs) ```python= def f2(**data2): print(data2) f2(person="Jhon", item="eraser", date="2022.10.17") ``` #### Reslult: {'person': 'Jhon', 'item': 'eraser', 'date': '2022.10.17'} ---- 另外,在宣告時 **任意參數**一定要放在**任意關鍵字參數** 前面 ```python= def my_function(arg0,arg1,*args,**kwargs): #to do... pass ``` --- # 函式(Function)種類 ### 無回傳值 前面有了 ### 有回傳值 ```python= def Sum(a,b): sum=0; for i in range(a,b+1): sum += i; return sum; print(Sum(2,10)) ``` #### Result: 54 --- # 函式(Function)變數範圍(Scope) **區域變數(Local Variable)** 和 **全域變數(Global Variable)** #### ex1: ```python= x=10 #全域變數 def number_is(): x=1000 #區域變數 print(x) number_is() print(x) ``` ---- #### Result: 1000 10 ---- #### ex2: ```python= x=10 def number_is(): global x x=1000 #強制更改全域變數 print(x) print(x) number_is() print(x) ``` #### Result: 10 1000 1000 --- # `lambda`函式(匿名函式) 匿名函式,顧名思義,就是沒有名字的函式,只有函式的實體 `lambda`函式可以接受任意數量的引數,但只能有一個表達式用作回傳。 ```python= x = lambda a, b : a * b print(x(5, 6)) # print((lambda a, b : a * b)(5, 6)) ``` ---- 等同於... ```python= def x(a,b): return a * b print(x(5, 6)) ``` ---- 常見的使用時機 ```python= scores = [ ('Jane', 'B', 12), ('John', 'A', 15), ('Dave', 'B', 11)] # 依照第三個數字元素排序 key = lambda s: s[2] scores.sort(key) # scores.sort(key = lambda s: s[2]) print(scores) ``` --- ## 更多內建函式庫 ```python= example1 = abs(-10) print(example1) #取得絕對值 輸出 10 example2 = chr(66) print(example2) #取得整數66的字元 輸出 B example3 = divmod(33,6) print(example3) #取得33除以6的商數和餘數 輸出 (5, 3) example4 = float(33) print(example4) #轉成浮點數 輸出 33.0 example5 = hex(33) print(example5) #轉成16進位 輸出 0x21 example6 = int(22.79) print(example6) #轉成整數(無條件捨去) 輸出 22 example7 = oct(33) print(example7) #轉成八進位 輸出 0o41 example8 = ord("B") print(example8) #取得Unicode編碼 輸出 66 example9 = pow(2,5) print(example9) #取得2的5次方 輸出 32 example10 = round(22.79) print(example10) #轉成整數(四捨五入) 輸出 23 example11 = sum([11,22,33,44]) print(example11) #取得list的總和 輸出 110 ``` ---- #### Reslut: 10 B (5, 3) 33.0 0x21 22 0o41 66 32 23 110 --- # 遞迴(題外話) 遞迴是一個常見的數學和程式概念。它意味著一個函式呼叫自己。 在使用遞歸時要非常小心,因為它很容易陷入一個永遠不會終止狀況,或者使用過量內存或處理器資源。但如果寫得正確,遞歸可以是一種非常高效和數學上優雅的編寫方法。 ---- 優點: (1)可增加程式的可讀性。 (2)可處理較複雜的問題。 缺點: (1)需要花費較多的時間。 (2)利用暫存堆疊(Stack)的觀念,需要額外的儲存空間。 ---- <!-- .slide: data-background="white" --> ### [Stack](https://zh.wikipedia.org/zh-tw/%E5%A0%86%E6%A0%88) ![](https://i.imgur.com/Gl4cYbJ.png) ---- ![](https://i.imgur.com/2r7BiIb.png) ---- ![](https://i.imgur.com/dEHSmnw.png) ---- #### 費式數列: ```python= def fibo(n): if n == 0: return 0 elif n == 1: return 1 return int(fibo(n-1) + fibo(n-2)) print(fibo(10)) ``` --- # 練習: ::: spoiler 練習1 ```python= def my_function(fname, lname): print(fname +' ' + lname) my_function('kk','jj') ``` ::: 執行下面程式碼會報錯,請修改第4行讓它能運行。 ```python= def my_function(fname, lname): print(fname + ' ' + lname) my_function('kk') ##改這行 ``` ---- ::: spoiler 練習2 ```python= def isPrime(n): if(n==2): return True for i in range(2,int(n**0.5)+1): if(n%i==0): return False return True print(isPrime(1117)) ``` ::: spoiler 寫一個含一個引數的函式(如下),判斷`n`是不是質數(回傳`True`或`False`)。 ```python= def isPrime(n): ## TO-DO print(isPrime(1117)) ``` :::success hint: 質數判斷邏輯,除了2其餘為奇數 ::: ---- ::: spoiler 練習3 ver.1.0 ```python= def func(n=int(input('輸入n:'))): for i in range(1,n+1): for j in range(i): print('*',end='') print() func() ``` ver.2.0 ```python= def func(n): #此function 為 印出一行 n 個星星 for i in range(n): print('*',end='') print() times=int(input('輸入n:')) for i in range(1,times+1): #執行function n次 func(i) ``` ::: 輸入: 整數n 輸出: nxn的直角三角形 ps使用function 輸入n:5 ![](https://i.imgur.com/1WAYEv5.png) ---- ::: spoiler 練習4 ```python= def mean(a,b,c): return (a+b+c)/3 print(mean(3,2,7)) ``` ```python= mean = lambda a,b,c : (a+b+c)/3 print(mean(3,2,7)) ``` ::: 輸入: `a,b,c` 輸出: 平均值 (也用可以用下面的`lambda`試試看) --- ## 參考資料 [Python 初學第七講 — 函式](https://medium.com/ccclub/ccclub-python-for-beginners-tutorial-244862d98c18) [[Python教學]5個必知的Python Function觀念整理](https://www.learncodewithmike.com/2019/12/python-function.html) [[Day05]Python 基礎語法 - function、import](https://ithelp.ithome.com.tw/articles/10201851) [[Python教學]Python Lambda Function應用技巧分享](https://www.learncodewithmike.com/2019/12/python-lambda-functions.html) [初學者學演算法|從費氏數列認識何謂遞迴](https://medium.com/appworks-school/%E5%88%9D%E5%AD%B8%E8%80%85%E5%AD%B8%E6%BC%94%E7%AE%97%E6%B3%95-%E5%BE%9E%E8%B2%BB%E6%B0%8F%E6%95%B8%E5%88%97%E8%AA%8D%E8%AD%98%E4%BD%95%E8%AC%82%E9%81%9E%E8%BF%B4-dea15d2808a3)

    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