Python Basics
Avoid Copy Pasting Code at All Cost
- Make sure you understand the code you write as much as you can.
- When you copy code, you bypass the cognitive process entirely.
- Even if the code you copied does work as intended, you have not learned much from pasting it.
Python Basics I
- Math operators
- Data types
- integer, float, string
type()to check the data type
- Variables
- Naming convention
- Clarity over brevity, e.g.,
fnis a bad name forfirst_name str(),int(), andfloat()for type conversion
- Comments
- Formatting strings using f-strings — the preferred way for this course
Markdown
Markdown is a text-to-HTML conversion tool for web writers. Markdown allows you to write using an easy-to-read, easy-to-write plain text format, then convert it to structurally valid XHTML (or HTML).
— https://daringfireball.net/projects/markdown/
A Jupyter Notebook has Markdown cells, where you can write formatted documents using Markdown.
Markdown Syntax
| What | How |
|---|---|
| Headings | one to six # symbols |
| Bold | **bold text** |
| Italic | *italic text* |
| Quote | > |
| Code | single backticks: `print('hello world')` |
| Code block | triple backticks |
| Unordered list | - (one dash) |
| Ordered list | 1. 2. 3. etc. |
| Nested list | use indentation |
| Hyperlinks | [Google](https://www.google.com/) |
See more at GitHub's basic writing and formatting syntax.
LaTeX
LaTeX is used to write math symbols and formulas inside Markdown cells.
- For inline mode, enclose the formula in
$...$ - For display mode (the formula is centered and displayed on its own line), enclose the formula in
$$...$$
Python Basics II
- Flow control
- Lists, dictionaries, and sets
- List/dict/set comprehension
- Functions and packages
Python Flow Control
List (Tuple) / Dictionary / Set
| Type | What it is | Syntax |
|---|---|---|
| List | ordered collection of values that can be changed (mutable) | [value1, value2, ...] |
| Tuple | a list that cannot be changed (immutable) | (value1, value2, ...) |
| Dictionary | unordered collection of key-value pairs with unique keys | {key1: value1, key2: value2, ...} |
| Set | unordered collection of values with unique (no duplicate) elements | {value1, value2, ...} |
How to Loop over a List / Dictionary
Use enumerate() when you need the index along with the value:
>>> animals = ['cat', 'dog', 'fish', 'elephant']
>>> for i, animal in enumerate(animals):
... print(f'Index {i} in animals list is: {animal}')
...
Index 0 in animals list is: cat
Index 1 in animals list is: dog
Index 2 in animals list is: fish
Index 3 in animals list is: elephantUse .items() to loop over the keys and values of a dictionary:
>>> customer = {'name': 'John', 'gender': 'male', 'age': 25}
>>> for k, v in customer.items():
... print(f'Key is {k}, Value is {v}')
...
Key is name, Value is John
Key is gender, Value is male
Key is age, Value is 25