ChaoChaoChao
    • 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 New
    • Engagement control
    • Make a copy
    • 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 Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
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
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
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 9001 python week 6 lists ## list and tuples ```python= a = ['Please Please Me', 'Help!', 'Abbey Road'] b = a print(a) print(b) b[1] = 'Let It Be' print(a) print(b) # a 和 b 指代的数组都变了。因为a,b没有新创地址存值,而是新值。 memory address! ``` ## sys.argv 的解释和使用 Another way for users to put in information is by using command line arguments. They are inserted when running the program in terminal, after the program name. To access these arguments, you will need to import sys module at the beginning of your program. sys.argv gives you all the command line arguments in a list of strings. The program name is always the first command line argument (with index 0)! ```python= import sys n_args = len(sys.argv) i = 0 while i < n_args: argument = sys.argv[i] # print(argument[0], end='') print(argument) # phonetic_spelling.py hotel echo lima lima oscar i += 1 print(sys.argv) # ['phonetic_spelling.py', 'hotel', 'echo', 'lima', 'lima', 'oscar'] ``` --- # 9001 python week 7 break ,continue , return break : To break out of a loop continue: To continue to the next iteration of a loop return: The return keyword is to exit a function and return a value. raise: To raise an exception * break may only occur syntactically nested in a for or while loop. * continue may only occur syntactically nested in a for or while loop. demo ```python= keep_running = True i = 0 while i < 10 and keep_running: j = 0 while j < 10 and keep_running: if i == 5 and j == 5: keep_running = False break print("i: {}, j: {}".format(i, j)) j += 1 print("hello") i += 1 ``` --- # 9001 python week 8 testing 作业要求: ## Explain the difference between **assert** and **raise** statements. **When** do you use these statements? ### Assert: 格式: assert <condition> , "This is an optional error message!" The assert statement will assess a Boolean condition that is given to it. If true: then nothing happend, if false: it will raise an ***AssertionError*** 用途:testing: This can be very useful for testing! We can take simple unit test cases and convert them quite easily into a series of assert statements - all we'd have to do is simply call the function with the correct inputs and compare the result against our expected output. demo: ```python= def some_function(a, b): if not isinstance(a, int) or not isinstance(b, int): return None return a + b assert some_function(1, 2) == 3, "Test case 1 failed." print("Test case 1 passed!") # These print statements are optional. assert some_function(0, 0) == 0, "Test case 2 failed." print("Test case 2 passed!") ``` Usually, however, tests are kept in a file that is **separate** from the code that we are looking to examine. This file is sometimes called a **test driver program**. ### Raise: Raise an exception To throw (or raise) an exception, use the raise keyword. ```python= x = -1 if x < 0: raise Exception("Sorry, no numbers below zero") ``` 也可以是 TypeError; ValueError ; ZeroDivisionError ### Test Driver 案例 1. Import the components that you want to test from your source code. 2. Define a function for each test case, using assert statements to enforce each one. 3. Call the functions as necessary. ```python= from some_program import some_function def test_happy_path_1(): assert some_function(1, 2) == 3, "Test case 1 failed." print("Test case 1 passed!") def test_happy_path_2(): assert some_function(0, 0) == 0, "Test case 2 failed." print("Test case 2 passed!") def test_invalid_type(): assert some_function("Oh no", 3) == None, "Invalid type mishandled." print("Invalid type handled correctly!") # ... and so on. # Run these tests if __name__ == "__main__": test_happy_path_1() test_happy_path_2() test_invalid_type() ``` --- ## Explain the difference between **end-to-end tests**, **integration test** and **unit test**. What type of testing did you **perform** in this question? * Unit Tests describe fast, simple tests that target the smallest possible. see the function is running correct or not. * Integration Tests examine how different components of a system interact with one another. * End-to-End Tests are large, complex tests that assess the full functionality of a system or program. ### Test Case Design * Positive test cases * Negative test cases * Edge cases --- End-To-End Testing 用diff bash command。 ```bash= diff a.py b.py ``` Unit Tests & white box 用 assert。 --- ## Are the **test cases** that you have generated sufficient to thoroughly test your program? Explain your answer. --- ## bash redirection & pipe * Input redirection ```shell= python3 print_num.py < number.txt (input redirection) ``` * Output redirection ```shell= python3 print_num.py < number.txt > out.txt && cat out.txt (combining input & output redirection) ``` * Pipe (This allows outputs (stdout) from program1 to be used as input (stdin) of program2.) ```shell= cat number.txt | python3 print_num.py pwd | cowsay ``` * diff (symbol: a for add, c for change, or d for delete) ```shell= diff groceries-a.txt groceries-b.txt ``` 进阶: ```shell= python3 [program name] < [test].in | diff - [test].out ``` ```shell= #! /usr/bin/env sh echo "##########################" echo "### Testing quadratic.py" echo "##########################\n" count=0 # number of test cases run so far # Assume all `.in` and `.out` files are located in a separate `tests` directory for test in tests/*.in; do name=$(basename $test .in) expected=tests/$name.out python3 quadratic.py < $test | diff - $expected || echo "Test $name: failed!\n" count=$((count+1)) done echo "Finished running $count tests!" ``` --- ## try / expect 使用 ```python= try: print(x) except: print("Something went wrong") else: print("no error") finally: print("The 'try except' is finished") ``` ```python= try: num = int(input("Enter first number: ")) denom = int(input("Enter second number: ")) print("{} divided by {} is {}.".format(num, denom, num/denom)) # except Exception: # print("Wait a second, what went wrong?") except ValueError: print("Please only enter integers!") except ZeroDivisionError: print("Division by zero is undefined :(") except: print("Wait a second, what went wrong?") ``` ***注意: 尽力不用Exception ,因为不知道具体哪里出了问题*** --- # 9001 python week 9 file ## read file ```python= filename = "alphabet.txt" f = open(filename, "r") print(f.read()) # 也可以显示要读字数的内容 eg:print(f.read(1)) ``` ```python= filename = "alphabet.txt" filea = open(filename, 'r') print("This is the start of the NATO phonetic alphabet:") while True: line = filea.readline() # 显示每一行 if line == "": break print(line) filea.close() ``` ## write file ```python= # Write to file filename = "shopping.txt" fobj = open(filename, "w") char = fobj.write("Coffee\n") print("Milk", file=fobj) fobj.close() ``` ## Extra: with You may have seen that we can open files (in any mode) in Python with a with statement, like so: ```python= with open('my_file.txt', 'w') as f: f.write('Hello world!') ``` --- # Week 10 Object ## Basic Class ```python= class <ClassName>: #It must always have the __init__(self, ...) function, #which is also known as the constructor of the class. #It constructs the class objects! init stands for initialise. def __init__(self, ...): pass <!-- just with init value --> class Fruit: def __init__(self, weight, sweetness, colour): self.weight = weight self.sweetness = sweetness self.colour = colour <!-- 创建对象 --> apple = Fruit(50, 90, 'red') <!-- 带function的 class --> class Fruit: def __init__(self, weight, sweetness, colour): self.weight = weight self.sweetness = sweetness self.colour = colour def value(self): return self.weight * self.sweetness apple = Fruit(10,5,'red') print(apple.value()) <!-- Static methods are methods that DO NOT depend on the instance. --> class Fruit: def __init__(self, weight, sweetness, colour): self.weight = weight self.sweetness = sweetness self.colour = colour def value(self): return self.weight * self.sweetness def total_value(list_of_fruits): total = 0 for fruit in list_of_fruits: total += fruit.value() # Call each fruit's value and add it. return total ls = [Fruit(10, 15, 'black'), Fruit(5, 50, 'red')] print(Fruit.total_value(ls)) ``` --- # week 11 Recursion ## 递归回顾 递归是解决问题的一种简单直观的方法。它的工作原理是反复将较大的问题分解为较小的问题,这些问题更容易解决。 递归有两个基本成分: 基本情况(要停止的地方) 递归关系(一种继续的方式) ```python= def print_num(n): if n<0: return print(n) print_num(n-1) print_num(5) ``` ## 扩展 DFS 和 BFS (不考) --- Python 中下划线的 5 种含义: https://www.runoob.com/w3cnote/python-5-underline.html ![](https://www.runoob.com/wp-content/uploads/2018/10/v2-cbc5c6037101c7d33cf0acd9f00a8cfa_r.jpg)

    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