Learning Python

Published: 2015-10-24

By: MJ Rossetti

Category:
Technologies:

Prerequisites

Install python. If using homebrew on Mac OS X: brew install python, and follow post-installation instructions.

Create a new project directory.

mkdir ~/Desktop/myApp
cd ~/Desktop/myApp

Python Package Management

Specify package dependencies, if necessary.

Add a file called requirements.txt to the root directory. Write the name of each required python package dependency on a new line, save the file, and exit.

numpy
django
git+https://github.com/eskerda/pybikes.git

Install package dependencies, if necessary.

pip install -r requirements.txt

Executing Python Scripts

Add a file called my_script.py to the root directory.

# my_script.py
print("DOING WORK HERE")

Run it.

python my_script.py

Python Debugging

Debug the script as necessary.

# https://gist.github.com/obfusk/208597ccc64bf9b436ed
import code
code.interact(local=locals())

Python Objects and Methods

Detect classes of objects.

type(my_obj) # or...
my_obj.__class__.__name__

Detect class methods and documentation.

dir(my_obj)
help(my_obj)

Python Object Types

dict, or dictionary, is like a hash

u, or unicode, is like a string

Convert dict to json object:

json.dumps(my_obj)

Python For Each Loops

# http://www.tutorialspoint.com/python/python_for_loop.htm
fruits = ['banana', 'apple',  'mango']
for fruit in fruits:
  print 'Current fruit :', fruit

Python Rescue from Exceptions

try:
  network_name = response.meta["name"].encode()
except UnicodeEncodeError:
  network_name = "#UNENCODABLE"
except UnicodeDecodeError:
  network_name = "#UNDECODABLE"