In Python, indent with 4 spaces. Irregular spacing will cause compile error.

print() will print or output from a script file such as script.py. Print can take multiple arguments, concatenated by a comma. Print will automatically include spaces:
print(var, var_two)
print(var, var_two, sep='') // override default space separator using sep

python script.py will compile and run script.

Comment in Python with # or """ My Comment """ for multiline comments.

Int and Float

Easy to learn, read yet powerful. Expansive library support (image processing, data analysis, creating games).

Python is an interpreted language. The Interpreter supports addition, subtraction, multiplication, division, exponent and negation.

Python has two number types, int (whole number) and float (floating point number).

Order of operations follows PEMDAS, Parentheses, Exponent, Multiplication, Division, Addition and Subtraction.

Division returns a float. Use interger division // to round down to nearest int.

int(value) // cast to an int

format(float, '.2f') // format a float to 2 decimal places using format. f for float, 2 decimal places.

Random numbers

import random
random = random.random() // returns a random number from [0.0, 1.0] random = random.choice([1,2,3,4,5]) // returns randomly from the passed in list random = random.randint(1, 1000) // returns randomly from a range.

Variables

swallow_limit = 60 / 3

Variables can help assign meaning to values.

Variables:
- cannot contain spaces
- cannot start with number or special character like $

Pep 8 Style Guide (Python Style Guide) recommends lowercase and underscore for spaces for Python variables. Pep 8 does not recommend camelCase.

To import a modules (for example Math) use import statement: import math.

Math has a method math.ceil(num) which will round up a number to nearest whole number. Math is included in Python standard library.

None Type

None type represents the absence of a value. None is falsey in conditional.

Strings

Strings are a sequence of characters. Create a string by surrounding in quotes, either '' or "". Strings can be stored in variables.

Concatenate strings using + operator.

\n in a string will add new line. \t will include tab in string.

To convert a number to string, use str(value).

str.strip() // remove all leading and trailing whitespace or new line characters.
str.split(' - ') // split string and return list of strings broken by passed in delimiter
str.replace(old, new[, max]) // if max provided, only the first count occurrances replaced

Strings are a list of characters. Each character has a zero indexed position.
Obtain character in position zero:

Greeting = "Hello"  
Greeting[0]  

len(str) returns length of a string
str[2:5] returns part of a string between the range: index at first number, index before second number. Can think of as markers prior to number. Leave out number to start at start str[:5], or go to end str[2:].

Conditionals

6 comparators in Python:
< <= == > >= !=

Conditional in Python works from indented code block. Nested conditionals okay.

if True or 'true':  
  print('true')
elif False or 'false':  
  print('false')
else:  
  print('not going here')

After a true, that code will be run and conditional will be exited.

Booleans can be be combine: True and True -> True, True and False -> False, True or False -> True.

input = input('Message') will print to user and wait for their input.

int(str) to cast string to int.

Lists and Dictionaries

Lists are containers that can store any type of data. These are the same as Arrays in JavaScript.
empty = [] // create empty list
mixed = ['string', 10] // create list of data

List items are ordered from index 0.
mixed[0] // return the item at index 0

Can also use the same splice syntax as strings, using range:
list[0:9] // return the index at first number, index before second number

list.append(item) // add to end of list
list.remove(item) // remove the item or if you know the index: del list[3]. del list[:3] can also take a range using the same syntax as splice.

len(list) // returns the length of a list.

Dictionaries map keys to values. These are the same as object literals in JavaScript. These can store any data in Python.
dict = { 'key' : 'value', 'key2' : 'value2 '}

Use the key to lookup a value:
dict['key'] // returns the value at key

A dictionary can map any type to any type (key doesn't need to be a string).

dict = {} // create an empty dictionary
dict['key'] = 'value' // add/update to dictionary using key lookup syntax and assign to value.

del dict['key'] // will delete the key-value pair from dictionary.

If use lookup method dict['key'] and it is not there, program will have KeyError. To avoid this, can use get method which will return None if no key-value pair.
dict.get('key') // will return None if not present.

dict.keys() // return a list of the keys
dict.values() // return a list of the values

List and Dictionary Comparisons

Can check lists and dictionaries for equality.

Equal lists have exactly the same items in exactly the same order. Since order of dictionaries doesn't matter, dictionary need to only have the key-value pairs to be equal.
list_or_dict == list_or_dict1 // returns True or False depending on equality.

Lists of lists sometimes called two dimensional list.
list[0][1] // return inner item of list of lists

Loops

for item in list:  
  total = total + item

range(count) // return a list of numbers of length count. i.e. range(10)
range(start, stop, step) returns a list of numbers, from start, stop and step values. i.e. range(1, 200, 2)

Can also access both key and value looping in dictionary:

for key, value in dict.items():  
  print(key, value)

While loops continue looping while a condition is True.

x = 1  
while x != 3:  
  print(x)
  x = x + 1

A break statement exits a loop immediately to run program outside the loop.
A continue statement will skip the current loop and continue to the next loop.

Functions

def name_of_function(parameter, another_param):  
  ...
  return parameter

name_of_function(list, value) // call function

Usual practice to put main code into a function called main, and call main from end of script.

Local and Global Scope

Scope determines what part of program can access certain variables. A variable declared within a function only has scope inside that function (local scope). A variable declared outside functions have global scope and can be accessed anywhere in the script.

Reading and Writing Files

Steps to write to a file:
1. Open file: open_file = open('filename.txt', 'w') // second param is mode: w for write, r for read and a for append.
2. Write to file: open_file.write('Some text\n') // need to add new lines
3. Close file: open_file.close()

Python will create file for write or append if the file doesn't exist. Write will overwrite file, use append instead to update.

Steps to reading from a file:
1. Open file: open_file = open('filename.txt', 'r') // r for read mode.
2. Read entire file contents: open_file.read()
2A. Read a line only: open_file.readline() // will keep track of line that on
3. Close file: open_file.close()

Can also read all lines in a for loop.

Exceptions

If open a file that doesn't exist, get a FileNotFoundError.

Use Try, Except to handle exceptions. Can assign error to variable and use in except block.

try:  
  file = open('filename.txt', 'r')
  print(file)
except ValueError as err:  
  print(err)

Python has over 60 types of exceptions.

Modules

Modules are libraries that contain functions. For example, import math or import random.
Pip is a package manager used to install modules:
pip install module_name

For example, HTTP requests:

import requests

request = requests.get('url')  
list = requests.json() // convert to JSON format  

Creating Modules

As program gets longer, may want to separate into separate modules and files.
A script containing definitions is a module and can be imported by a script or another module. As long as files are in the same directory, can import modules using import filename.

Need to namespace function calls with module name to access imported module functions.