the zen of python
there should be one
and preferably only one
obvious way to do it
basics
-
whitespace formatting
-
whitespace is ignored inside parentheses and brackets
long_winded_computation = (1 + 2 + 3 + ... + 12 + 13 + 14 + 15 + ... + 20)
-
making code easier to read
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] easier_to_read = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
-
backslash to indicate continues on next line
two_plus_three = 2 + \ 3
-
hard to copy and paste
for i in range(1, 6): # notice the blank line print i # paste into python shell IndentationError: expected an indented block # in ipython shell # use magic %paste
-
-
modules
-
import
import re my_regex = re.compile('[0-9]+', re.I)
-
alias
import re as regex my_regex = regex.compile('[0-9]+', re.I)
-
standard convention
import matplotlib.pyplot as plt
1.without qualification
from collections imiport defaultdict, Counter lookup = defaultdict(int) my_counter = Counter()
-
-
arithmetic
# a = 2 a = 5 / 2 from __future__ import division # a = 2.5 a = 5 / 2 # a = 2 a = 5 // 2
-
functions
-
use
def
def double(x): """docstring""" return x * 2
-
functions are first-class
def apply_to_one(f): """calls the function f with 1 as its argument""" return f(1) my_double = double x = apply_to_one(my_double)
-
assign lambda to variables
# don't do this another_double = lambda x: x * 2 # do this instead def another_double(x) return x * 2
-
default arguments
def my_print(message="my default message"): print message my_print('hello') my_print() def substract(a=0, b=0): return a - b substract(10, 5) substract(0, 5) substract(b=5)
-
-
strings
-
single or double quotation
-
encode special character
tab_string = '\t' len(tab_string)
-