resources

libraries

language

  • Interpreted programming language
    • Easier to write and test
    • Slower than compiled languages
  • Shallow copy: constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
  • Deep copy: constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

basics

  • No need to declare types

functions

  • def is the keyword for defining a function

numbers

  • ** for powers

text

  • Strings immutable
  • If you don’t want characters prefaced by \ to be interpreted as special characters, you can use raw strings by adding an r before the first quote
  • Strings can be concatenated (glued together) with the + operator, and repeated with *
  • Indices for characters may also be negative numbers, to start counting from the right
  • Slice: [index:index] (last index excluded)

lists

  • Mutable
  • Can concatenate
  • Like arrays
  • Simple assignment never copies data
  • Slice operations return shallow copy
  • Can nest

if

x = int(input("Please enter an integer: "))

if x < 0:
    x = 0
    print('Negative changed to zero')
elif x == 0:
    print('Zero')
elif x == 1:
    print('Single')
else:
    print('More')

for

# Create a sample collection
users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}

# Strategy:  Iterate over a copy
for user, status in users.copy().items():
    if status == 'inactive':
        del users[user]

# Strategy:  Create a new collection
active_users = {}
for user, status in users.items():
    if status == 'active':
        active_users[user] = status

range

  • range(start, end, step)

break & continue

  • break statement must be followed by else
for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print(n, 'equals', x, '*', n//x)
            break
    else:
        # loop fell through without finding a factor
        print(n, 'is a prime number')

match

  • Similar to switch

list comprehension

[expression for item in iterable]

e.g.

dim_args = ['+'.join(d) for d in dimensions]

yield

  • yield: used to create generators, iterators that allow values to be produced lazily, one at a time, instead of returning them all at once

context management

with open('file.txt', 'w') as f:
    f.write('Hello!')

=

f = open('file.txt', 'w')
try:
    f.write('Hello!')
finally:
    f.close()

utility functions

  • dir(): display contents of an object
  • separator.join(iterable)
  • any(): returns True if any of the elements of a given iterable( List, Dictionary, Tuple, set, etc) are True else it returns False

quirks

mutable default arguments

Create a new object each time the function is called, by using a default arg to signal that no argument was provided (None is often a good choice).

def append_to(element, to=None):
    if to is None:
        to = []
    to.append(element)
    return to

Python’s default arguments are evaluated once when the function is defined, not each time the function is called (like it is in say, Ruby). This means that if you use a mutable default argument and mutate it, you will and have mutated that object for all future calls to the function as well.

Sometimes you can specifically “exploit” (read: use as intended) this behavior to maintain state between calls of a function. This is often done when writing a caching function.