BANA409BANA409

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., fn is a bad name for first_name
    • str(), int(), and float() 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

WhatHow
Headingsone to six # symbols
Bold**bold text**
Italic*italic text*
Quote>
Codesingle backticks: `print('hello world')`
Code blocktriple backticks
Unordered list- (one dash)
Ordered list1. 2. 3. etc.
Nested listuse 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

TypeWhat it isSyntax
Listordered collection of values that can be changed (mutable)[value1, value2, ...]
Tuplea list that cannot be changed (immutable)(value1, value2, ...)
Dictionaryunordered collection of key-value pairs with unique keys{key1: value1, key2: value2, ...}
Setunordered 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: elephant

Use .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

Cheat Sheets

In-Class Group Exercise

On this page