NISRA
  • NEW!
    NEW!  Connect Ideas Across Notes
    Save time and share insights. With Paragraph Citation, you can quote others’ work with source info built in. If someone cites your note, you’ll see a card showing where it’s used—bringing notes closer together.
    Got it
        • 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 No publishing access yet

        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.

        Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

        Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

        Explore these features while you wait
        Complete general settings
        Bookmark and like published notes
        Write a few more notes
        Complete general settings
        Write a few more notes
        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 New
      • Engagement control
      • Make a copy
      • 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 Note Insights Versions and GitHub Sync Sharing URL Help
    Menu
    Options
    Engagement control Make a copy 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 No publishing access yet

    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.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    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
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    :::info # Python 講師:white 時間:8/27 10:00~12:00 課程簡報: https://docs.google.com/presentation/d/1P88y2jwDgaW_vLbzHduc-ioi653yo2N-eoO3ACZrbDQ/edit?usp=sharing 課程程式碼範例檔案: https://drive.google.com/drive/folders/1A1qOoZ-nBJf9EQVSEMmvQ4XrlSpgbXF9?usp=sharing ::: ## 大綱(Outline) 1. [Python 安裝](#Python-安裝) 2. [資料型態與基本語法](#基本語法) 3. [控制結構](#控制結構Control-Structures) 4. [迴圈](#迴圈Loops) 5. [函式](#函數Functions) 6. [類別](#類別Class) 7. [模組](#模組) 8. [凱薩密碼實作](#凱薩密碼Caesar-Cipher) ## Python 安裝 - 到 Python 官網下載 `.exe` - 官網:<https://www.python.org/downloads/> ![python install](https://hackmd.io/_uploads/HkAhRHotll.png) - Visual Studio Code ![vscode extension install](https://hackmd.io/_uploads/r1XJyLsKlx.png) ## 基本語法 ### 資料型態(Data Types) - **資料**:程式中數據的基本單位 - **資料型態**:資料的分類 | 類型 | 說明 | 範例 | | ------- | --- | ---------------- | | `int` | 整數 | 1、2、3、… | | `float` | 浮點數 | 1.1、1.01、1.001、… | | `bool` | 布林值 | `True`、`False` | | `str` | 字串 | `"ABC"` 、 `'NISRA'` | 註: python 使用 單引號或雙引號都可以表示成字串 - **list(陣列)**:一種有順序、可變動的資料集合 ```python= data = [1, 2, 1.1, 'Hello', True] data.append(3) print(data) print(data[0]) #1 print(data[-1]) #3 print(data[0:2]) #[1, 2] print(data[1:]) #[2, 1.1, "Hello", True, 3] print(data[:]) #[1, 2, 1.1, "Hello", True, 3] ``` - **dictionary(字典)**:`key-value` 資料組合 ```python= data = { 'a': 123, 'b': 3.14159, 'c': False, 'd': 'Hello', 'e': [456, 7.89, True, 'World'] } print(data) print(data["a"]) # 123 print(data["e"][1]) # 7.89 ``` ## IO #### User Input ```python= user_input = input('Enter anything: ') ## Default input is string print(user_input) print(type(user_input)) int_input = int(input('Enter a number: ')) ## Convert input to integer print(int_input) print(int_input + 1) print(type(int_input)) split_input = input('Enter two number: ').split() ## Split input by space print(split_input) print(type(split_input)) ``` #### Print ```python= name = 'Example' number = 123 print(name, number) print('{} {}'.format(name, number)) print(f'Name: {name}, Number: {number}) # Example 123 ``` ## Operators | 類別 | 運算子 | | -------------------- | ----------------------------------- | | Arithmetic Operators | `+`, `-`, `/`, `*`, `%`, `//`, `**` | | Assignment Operators | `=`, `+=`, `-=`, `*=`, `/=` | | Comparison Operators | `==`, `!=`, `<`, `>`, `<=`, `>=` | :::warning `縮排` 和 `:` 在 python 中是很重要的!!! ::: ## 控制結構(Control Structures) ### 基本語法 `if` 語法結構: ```python if (布林值): # 若布林值為 True 執行 ``` 語法示範: ```python= a = 123 if a == 123: print('a is 123') ``` ```python= a = 456 if a == 123: print('a is 123') print('end') ``` ### 基本語法 `if-else` 語法結構: ```python if (布林值): # 若布林值為 True 執行 else: # 若布林值為 False 執行 ``` 語法示範: ```python= a = 5 if a > 5: print('a is more than 5') else: print('a is less than 5') ``` ### 基本語法 `if-elif-else` 語法結構: ```python if (布林值): # 若布林值為 True 執行 elif (布林值): # 若布林值為 True 執行 else: # 若兩個布林值都是 False,執行 ``` 語法示範: ```python= a = 5 if a > 5: print('a is more than 5') elif a == 5: print('a is 5') else: print('a is less than 5') ``` ### Lab01 Simple Calculator #### Sample Input: ``` 3 + 2 3 - 2 3 * 2 3 / 2 ``` #### Sample Output: ``` 5 1 6 1 ``` ## 迴圈(Loops) ### `for` 迴圈 語法結構: ```python for 變數名稱 in (串列 or 字串): # 程式碼 ``` 將串列中的項目 / 字串中的字元逐一取出 語法範例: ```python= data = [1, 2, 3, 4, 5] for i in data: print(i, end=' ') ``` ### `for` & `range()` 函數 語法結構: ```python for 變數名稱 in range(a, b, c): # 程式碼 ``` `a` = 起始點、`b` = 結束點、`c` = 增加值 - `a` 可省略,預設為 `0` - `c` 可省略,預設為 `1` 語法範例: ```python= a = [] for i in range(1, 5): a.append(i) print(a) # [1, 2, 3, 4] b = [] for i in range(1, 5, 2): b.append(i) print(b) # [1, 3] c = [] for i in range(5): c.append(i) print(c) # [0, 1, 2, 3, 4] ``` ### `while` 迴圈 語法結構: ```python while (布林值): # 布林值為 True 時執行 ``` 語法範例: ```python= a = 0 while a < 5: print(a, end=' ') a += 1 ``` ```python= a = 0 while True: print(a, end=' ') a += 1 if a > 5: break ``` ### Lab02 Square Printer **Sample Input:** ``` 2 3 2 4 3 ``` **Sample Output:** ``` ### ### #### #### #### ``` ## 函數(Functions) - 函式:包裝在一個區塊內的程式碼,方便重複呼叫使用 - 先**定義**(建立)函式,才能**呼叫**(使用)函式 ### 定義函式 ```python= def 函式名稱(參數名稱): # 程式碼 return () # 程式結束點、return 內可以寫資料、參數或是變數 ``` ### 呼叫函式 ```python 函式名稱(參數資料) ``` ### 範例 ```python= def area(width, height): ans = width * height return ans print(area(10, 20)) ``` ## 類別(Class) - 一種 "藍圖" - 帶有獨立不同的屬性 / 設定 - 可以依照不同的藍圖建構出不同的物體 ```python= class Car(): def __init__(self): ## 建立預設屬性 self.brand = 'Toyota' self.wheel = 4 self.color = 'Red' self.price = 1000000 myCar = Car() print(myCar.brand) print(myCar.wheel) print(myCar.color) print(myCar.price) ``` ### 建立類別 ```python= class Car(): pass ``` ### `__init__` - 建立預設屬性 / 預設資料 - 帶有 `self` 參數代表建立的物件 - 可省略不定義 ```python= class Car(): def __init__(self): ## 建立預設屬性 self.brand = 'Toyota' self.wheel = 4 self.color = 'Red' self.price = 1000000 ``` ### 類別中建立功能 - 在 class 中增加函數 - 執行和該類別有關的功能 - 增加類別物件安全性 ```python= class Car(): def __init__(self): ## 建立預設屬性 self.brand = 'Toyota' self.wheel = 4 self.color = 'Red' self.price = 1000000 def get_Price(self): print(self, price) def set_Price(self, price): self.price = price def sell(self, customer): print(self.brand + "的車子賣給了" + customer) myCar = Car() myCar.get_Price() myCar.set_Price(2000000) myCar.get_Price() myCar.sell('John') ``` ## 模組 - 存在於其他任意檔案的程式碼 / 類別 - 分類 - 內建模組 - 標準庫模組 - 第三方模組 - 自訂模組 (自製模組) ### 引用模組 - import ... - from ...import ... 範例: ```python= import datetime from datetime import date print(datetime.datetime.now()) print(data.today()) ``` ```python= import math print(math.pi) print(math.fabs(-3.14)) print(math.sqrt(64)) ``` ### 自訂 / 自製模組 - 將共用的程式打包成模組,透過其他程式的引用 - 自訂函式的檔案要和使用的程式檔放在一起 ```python= # Test.py def talk(msg): print(msg) def add(a, b): return a + b def sub(a, b): return a - b ``` ```python= import Test Test.talk('Hello') print(Test.add(1, 2)) print(Test.sub(1, 2)) ``` ## 凱薩密碼(Caesar Cipher) - 替換式加密 - 架構: ```mermaid flowchart LR; A[明文] --字母表偏移--> B[密文] ``` ![ASCII Table](https://hackmd.io/_uploads/Hkf_DkhKge.png) ### 範例 - 密文to明文 ```mermaid flowchart LR; A[密文:<br><code>attackatonce</code>] --偏移量=5--> B[明文:<br><code>exxegoexsrgi</code>] ``` - 明文to密文 ```mermaid flowchart LR; A[明文:<br><code>udymtsnxymjgjxy</code>] --偏移量=5--> B[密文:<br><code>pythonisthebest</code>] ``` ### 相關函式 - `ord()`:把字母變成 ASCII code - `chr()`:把 ASCII code 變成字母 ### 範例程式 #### 凱薩加密 ```python= def caesar_encrypt(text: str, shift: int): result = '' for ch in text: if 'A' <= ch <= 'Z': result += chr((ort(ch) - ord('A') + shift) % 26 + ord('A')) elif 'a' <= ch <= 'z': result += chr((ort(ch) - ord('a') + shift) % 26 + ord('a')) else: result += ch key = int(input('Please input the shift: ')) msg = input('Please input the message: ') cipher = caesar_encrypt(msg, key) print('密文:', cipher) ``` #### 凱薩解密 ```python= def caesar_decrypt(cipher_text: str, shift: int): return caesar_encrypt(cipher_text, -shift) key = int(input('Please input the shift: ')) msg = input('Please input the message: ') cipher = caesar_decrypt(msg, key) print('明文:', cipher) ``` ### Lab03: Caesar Cipher Encrypter / Decrypter #### Sample Input case 1: ``` encrypt HelloWorld 5 ``` case 2: ``` decrypt OlssvDvysk 7 ``` #### Sample Output case 1: ``` 密文: MjqqtBtwqi ``` case 2: ``` 明文: HelloWorld ``` ### Lab - 03 提示 1. 獲取使用者輸入 2. 判斷功能 3. 運算後輸出對應資訊 ### Lab04 Caesar Cipher Shift Counter #### Sample Input case 1: ``` MjqqtBtwqi HelloWorld ``` case 2: ``` OlssvDvysk HelloWorld ``` #### Sample Output ``` case 1: The shift is 5 case 2: The shift is 7 ``` ### Lab - 04 提示 1. 獲取使用者輸入 2. 執行字串判斷 3. 判斷直到獲取正確偏移量 ### Lab05 Caesar Cipher Function Debug ```python encrypted_flag = "UPZYH{wFao0uJhLzhYjyfWa}" def caesar_decrypt(s, shift): result = "" for i in range(len(s)-1,0,-1): c = s[i] if 'a' <= c <= 'z': result += chr((ord(c) - ord('a') + shift) % 26 + ord('a')) elif 'A' <= c <= 'Z': result += chr((ord(c) - ord('A') + shift) % 26 + ord('A')) else: result += c return result print("Decrypted:", caesar_decrypt(encrypted_flag, 7)) ``` --- ###### tags: `2025 NISRA Enlightened` <style> .navbar-brand::after { content: " × NISRA"; } </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
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    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