CSCI0200
      • 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
      • 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
    • 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 Help
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
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
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: resources --- # CS200 Python Style Guide ## Introduction By this point, you're all Java styling wizards. Now it's time to learn Python! Luckily for you, lots of style points are the same between the two languages, but there are some differences that will be outlined in this document. Be sure to read this thoroughly and *in its entirety* so your code is well-styled in Python (remember, you are partially graded on style :wink:). ## Naming Please give variables and functions useful names! ### Modules Module names are all lower case, with consecutive words concatenated together (like packages in Java!). Try to keep your module names as short as possible while still being descriptive. For example: `mymod` ### Classes Class naming conventions in Python is identical to Java! :::spoiler Click here for a refresher! Classes should be named using nouns which describe what the class models. Class names should be written in UpperCamelCase, in which words are concatenated and every word starts with an uppercase letter. For example: `Ocean` and `TreeHouse` ::: <br> :::info Exceptions in Python are also classes! Keep in mind, exception names should always end with "Error." For example: `BadDataError` ::: ### Constants Constant naming conventions in Python is identical to Java! :::spoiler Click here for a refresher! Constants should have names consisting of nouns describing their content. Constant names are written in `CONSTANT_CASE`: all uppercase letters with words separated by underscores. For example: `MY_PYTHON_CONSTANT` ::: ### Everything Else **This includes functions, fields, parameters, and variables** Everything else is written in `snake_case`, in which all letters are lowercase with words separated by underscores. For example: `my_variable` and `exciting_new_method` ## Formatting ### Indentation In Python, indentation is a must. Your code will not compile or run properly if you don't have the correct indentation. It can be a little finicky, though: if you use spaces to indent in some places and tabs in another your compiler will not be happy. In CS200, you should use **4 spaces** to indent all blocks of code. :::info You can configure your VSCode to automatically insert 4 spaces when the tab key is pressed. In the bottom right of your window in VSCode, there's a portion that will say "Spaces: \<number\>" or "Tab Size: \<number\>." Click on that and choose "Indent using spaces" followed by "4" to have the correct settings. When you're done you should see "Spaces: 4" in the bottom corner of your code window. ::: A new block or block-like construct in Python is preceded by a colon (`:`). Like in Java, the code within each new block should be indented by four spaces relative to the previous level. When the block ends, the indent level should return to the previous level. *This indent level applies to both code and comments throughout the block.* ```python def check_adult(age): if age >= 18: print("You are officially an adult!") else: print("Not an adult yet...") ``` ### Line Wrapping Lines of code should **never exceed 80 characters in length**, as anything longer than that becomes less and less readable. Such lines should be wrapped appropriately. Since Python is much more finnicky about spacing than Java is, there are a couple of rules that must be followed when wrapping lines: 1. All wrapped lines must keep the same level of indentation as the original statement 2. When wrapping on operators, the operator must start the new line For example: ```python # This is correct long_argument_name = even_longer_argument_name + yet_another_even_longer_name # This is not correct long_argument_name = even_longer_argument_name + yet_another_even_longer_name # This is also not correct long_argument_name = even_longer_argument_name + yet_another_even_longer_name ``` Another neat trick about line wrapping in Python is the backslash (`\`) character. Using the backslash at the end of a line indicates to the compiler that the expression will be continued on the next line (i.e. it's a signal that you'll be wrapping). Here's a few ways it might come in handy: ```python # This is correct now! long_argument_name = even_longer_argument_name \ + yet_another_even_longer_name # And so is this! long_argument_name = even_longer_argument_name + \ yet_another_even_longer_name ``` Note that when wrapping with the backslash, the wrapped line of code must be indented so that the first character of the wrapped line is inline with the beginning of the expression on the original line (in this case, the equality operator). ## Commenting The general principle of commenting is the same regardless of what language you're coding in: to clarify / explain your code to an outside observer (or to your future self!). Like in Java, you will have implementation and documentation comments in your Python code, but the syntax is somewhat different so let's go over that quickly. ### Implementation Comments All implementation comments (whether they be multi-line, single-line, or end-of-line) should begin with a `#`. Here's what your implementation comments should look like: ```python # This is a multi-line implementation # comment in Python! # This is a single-line one x = 5 # and this is an end-of-line comment ``` ### Documentation Comments Also known as a "docstring," documentation comments in Python have a slightly different (and less picky) format than Javadoc comments have in Java. Docstrings in Python appear directly *underneath* the declaration of each function. They should have the following format: * One sentence summary of the function (what it does / its purpose) * Parameter descriptions (if any) * Return value descriptions (if any) * Exceptions thrown (if any) * Anything else (i.e. are there restrictions on calling this function, does the function have any side effects) For example: ```python def sum(x: float, y: float) -> float: """Sums two numbers Parameters: x -- the first number y -- the second number Returns: A number (the sum of x and y) Throws: BadInputError if x or y (or both) is not a number """ ``` All functions require type annotations on inputs and output. You can omit output annotation for functions that have no return (for example functions that only need to `print`). Write docstrings for all functions, including helper and nested functions. A good docstring gives a description of the function, including its input(s), output, and purpose. Ideally, by looking at the docstring you know what the function does and how to use it without looking at the function body itself. ## Other Important Notes ### `self` Keyword In Python, we use the keyword `self` to access methods and fields that are defined within the class they're referenced from. You should **always** use `self` when appropriate. The `self` keyword is very similar to the `this` keyword in Java. The primary difference between `self` and `this` is that `self` must be used as the first parameter for a method inside a Python class: ```python= class Food: # init method or constructor def __init__(self, fruit: str, color: str) -> None: self.fruit = fruit self.color = color def show(self) -> None: print("fruit is", self.fruit) print("color is", self.color) ``` ### Import Statements Just like in Java, you must import predefined classes or modules (or functions) before being able to use them in your code. When importing, you are free to import either the specific class or the module itself. For example, if you wanted to use the `randint` function from the `random` module, it would be acceptable to do either of the following: ```python from random import randint # code in between num = randint(1, 10) ``` or ```python import random # code in between num = random.randint(1, 10) ``` ### Other Style Tips 1. Use constants where appropriate. 2. Use helper functions where appropriate. 3. Make sure your helper functions and constants are not redundant. There is no point in making this function: ```python def string_to_lower(s: str) -> str: return s.lower() ``` since you could always use `s.lower()` instead. 4. `return` statements should be not be written like this: ```python return(value) ``` but rather like this: ```python return value ``` 5. `if` statements should be written with newlines: ```python if condition1: print('condition1') elif condition2: print('condition2') else: print('condition3') ``` --- *Please let us know if you find any mistakes, inconsistencies, or confusing language in this or any other CS200 document by filling out the [anonymous feedback form](https://forms.gle/JipS5Y32eRUdZcSZ6)!* *(you do have to sign in but we don't see it)*

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