ts-boring
    • 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
    <!--introduction--> # 11/8 第九堂社課 ## 今日講師:R緯 #### (Python班) --- # 今日課程主題: ---- # 介紹函式 (function) ---- # 回傳值 (return) ---- # 複習(?)-變數範圍 (scope) ---- # 歡樂題目time --- # 介紹函式 (function) ---- ## 函式長怎樣? 定義函式 ```python= def 函式名稱(參數): 程式碼 ``` 呼叫函式 ```python= 函式名稱(參數) ``` ---- 定義函式:將一段程式碼打包起來,變成一個函式 呼叫函式:需要用到該段程式碼時,用函式叫出來 簡單來說...數學的函數 [老捧油-scratch](https://scratch.mit.edu/projects/editor/?tutorial=getStarted) ---- 舉例#1 \begin{align}f(x)=(x+4)(6x^2+8x-4)+5x\end{align} 用python函式做做看 ---- ```python= x = int(input()) print((x + 4)*(x**2 + 8*x - 4) + 5*x) ``` ```python= def f(x): print((x + 4)*(x**2 + 8*x - 4) + 5*x) #1~2行 定義函式 f(int(input())) #5行 呼叫函式 ``` ---- ## 函式可以讓程式看起來比較乾淨 ---- 例題#1 請撰寫一個Python函式 $\texttt{reverse_string(s)}$,該函式輸入一個字串s作為參數,並返回該字串的反轉版本。 ---- ```python= def reverse_string(s): for i in range(len(s) - 1, -1, -1): print(s[i], end="") reverse_string(input()) ``` ```python= def reverse_string(s): print(s[::-1]) reverse_string(input()) ``` --- # 回傳值 (return) ---- 1. 用途: 傳遞結果:將計算結果返回給呼叫者。 控制流程:提前結束函式執行。 2. 返回多個值: 可以同時返回多個值,並以元組形式接收。 ---- ```python= def f(a, b, c): return a**2 + b**2 + c**2 ``` $\texttt{return}$的意思就是把程式碼的$\texttt{f(a,b,c)}$換成\\(a^2 + b^2 + c^2\\) ---- 注意事項: 無$\texttt{return}$時預設返回$\texttt{None}$。 $\texttt{return}$後的代碼不會執行。 ---- 舉例#1 請撰寫一個Python函式$\texttt{find_max_min(numbers)}$,該函式接受一個數字列表$\texttt{numbers}$作為參數,返回最大值和最小值(Max, Min)。如果列表為空,則返回 (None, None)。(本題以EOF結束) ---- input ```python 3 1 4 1 5 9 2 6 -10 -20 0 5 3 #這行是沒東西 ``` output ```python (9, 1) (5, -20) (None, None) ``` ---- ```python= def find_max_min(numbers): if not numbers: # 檢查列表是否為空 return (None, None) max_value = max(numbers) # 找到最大值 min_value = min(numbers) # 找到最小值 return (max_value, min_value) try: while 1: numbers = list(map(int, input().split())) print(find_max_min(numbers)) except EOFError: None ``` ---- 例題#2 請寫一個Python函式$\texttt{calculate_average(args)}$ ,該函式接受多個數字作為參數,並返回這些數字的平均值(必為整數)。如果沒有提供任何數字,則返回 0。(本題以EOF結束) ---- ```python= def calculate_average(args): if not args: return 0 return sum(args) // len(args) try: while 1: numbers = list(map(int, input().split())) print(calculate_average(numbers)) except EOFError: None ``` --- # 複習(?)-變數範圍 (scope) ---- ### 變數的範圍(scope)主要有四種 1. 全域變數(Global Variables) 1. 區域變數(Local Variables) 1. 封閉變數(Enclosing Variables) 1. 內建變數(Built-in Variables) ---- ## 全域變數(Global Variables) 在函數或類別外定義的變數。 在**整個程式**中都可以存取和修改。 ---- ```python= x = 10 # 全域變數 def my_function(): print(x) # 可以在函數內部存取全域變數 my_function() # 輸出 10 ``` ---- ## 區域變數(Local Variables) 在函數或類別方法內部定義的變數。 只能在**定義區域內**存取和修改。 當函數或方法執行完後,區域變數會被銷毀。 使用$\texttt{global}$關鍵字可以改成全域變數。 ---- ```python= def my_function(): y = 5 # 區域變數 print(y) my_function() # 輸出 5 # print(y) # 錯誤,y 在函數外部不可見 ``` ```python= def my_function(): global y y = 5 # 區域變數 print(y) my_function() # 輸出 5 print(y) # 輸出 5 ``` ---- ## 封閉變數(Enclosing Variables) 在外層函數中定義的變數。 可以在內層函數中存取和修改。 使用$\texttt{nonlocal}$關鍵字可以在內層函數中存取和修改封閉變數。 ---- ```python= def outer_function(): x = 10 # 封閉變數 def inner_function(): y = 5 # 區域變數 print(x) # 可以存取封閉變數 inner_function() outer_function() # 輸出 10 def modify_enclosing(): x = 10 def inner(): nonlocal x x = 20 # 使用 nonlocal 關鍵字修改封閉變數 inner() print(x) # 輸出 20 modify_enclosing() ``` ---- ## 內建變數(Built-in Variables) ### 通常叫 內建函式(Built-in Functions) Python 內建的一些變數和函式,例如$\texttt{print()}$, $\texttt{len()}$, $\texttt{range()}$ 等。 在整個程式中都可以存取和使用。 [Python官方-內建函式](https://docs.python.org/3.13/library/functions.html) ---- Python會按照以下的搜尋順序來尋找變數: 1. 當前(區域)作用域(Local) 1. 封閉作用域(Enclosing) 1. 全域作用域(Global) 1. 內建作用域(Built-in) 如果在上述作用域中都找不到該變數,則會引發$\texttt{NameError}$異常。 ---- 簡單觀念題 在以下程式碼中,輸出的值是多少? ```python= x = 5 def my_function(): x = 10 print(x) my_function() ``` https://rate.cx/rate?9270A3 https://rate.cx/PieCharts?9270A3 --- # 歡樂題目time ---- 例題#3 --- # END

    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