Python cheatsheet

12 min. read

Caution! This article is 6 years old. It may be obsolete or show old techniques. It may also still be relevant, and you may find it useful! So it has been marked as deprecated, just in case.

From today on, I have new tasks and responsibilites at work, for which I need to learn Python and Django. Very timely, this weekend was CodeSchool's free weekend, something I saw for the first time in February this year. It's a weekend where all their courses and screencasts are FREE.

So just as the previous free weekend, I literally locked myself up at home and followed four of their courses: Try Python, Flying through Python, Try Django and Digging into Django, as well as the related screencasts.

Of course two days is not enough to master a new programming language and a new web framework, but I did absorb a lot and was able to make contributions at work from the first moment, first through pairing, and then alone. So I am very proud of myself!

This post is to compile my notes of the Python courses so that I can reference them in the future, as some sort of cheat-sheet.

"Try Python" - notes

First I checked if I had python installed:

$ python
Python 2.7.6 (default, Oct 26 2016, 20:30:19)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> quit()

This command also works kind of like irb in Ruby.

Next, I checked which versions I have installed:

$ which python
$ ls /usr/bin/python*
python            python2.7         python2-config    python3.3
python3.4         python3m          pythontex         python2
python2.7-config  python3           python3.3m        python3.4m
python-config     pythontex3

So, to run a script:

$ python


$ python3.4

Some concepts:

  • PEMDAS = Parenthesees, Exponent, etc. Refers to the order of evaluation of expressions.
  • exponent:
    variable_name = 4.1 ** 2
  • Print prints a line:
    print str(4/2)  # 2.0 (not in Python 2, where they are the same)
    print str(4//2) # 2   (not in Python 2, where they are the same)
  • Importing modules
    import math
    x = math.ceil(variable_name)
  • Strings:
    first_name = 'Monty'
    last_name = 'Python'
    full_name = first_name + ' ' + last_name
    print(first_name, last_name)
    # ('Monty', 'Python')
    print full_name # (Python 2+)
    # Monty Python
    year = 1969
    print 'They started in ' + str(year)
    # They started in 1969
    print('this is another way, but remove parentheses!', year)
    # ('this is another way, but remove parentheses!', 1969)
    print 'like this', year
    # like this 1969
    quotes = "foo' bar"
    print quotes
    # foo' bar
    famous_sketch1 = "\n\tHell's Grannies"
    famous_sketch2 = '\n\tThe dead Parrot'
    print 'Famous Work:', famous_sketch1, famous_sketch2
    # Famous Work:
    # 	Hell's Grannies
    # 	The dead Parrot
    # strings are arrays of letters
    foo = 'foobar'
    print foo[0]   # f
    print len(foo) # 6
    print foo[2:5] # oba (like two markers before |234|5)
    print foo[:3]  # foo
  • Logical operators: same as Ruby, BUT:
    foo = True
    bar = False
  • Indentation: 4 spaces, or be consistent.
  • if has no parentheses, and no end
    x = 3
    if x <= 0:
        print 'foo'
    elif x > 0 and x < 5:
        print 'hahaha'
        print 'bar'
        print 'hey'
    if foo:
        # foo is truthy or falsey
  • None is like null or nil:
    if user is not None:
        # do something
  • Standard input/output:
    boo = input('Type something: ') # Needs quotes
    print 'You entered', boo
    boo = raw_input('Type something: ') # old versions of python
    print 'You entered', boo
  • Casting:
    also, str(42) works like a casting.

"Fllying through Python" - notes

  • Lists are arrays, and can mix types:
    x = [1, 'hey', True]
  • You can make a lot of operations:
    print(x[2:]) # [True]
    print(x)     # [1, 'hey', True]
    print(x)     # [1, 'hey', True, 'foo']
    print(x)     # ['hey', True, 'foo']
    del x[0]
    print(x)     # [True, 'foo']
  • Dictionaries are hashes:
    # the elements change order everytime you print them
    anything = {}
    anything = {10: 'hello', 2: 123.45}
    anything['knackered'] = 'tired'
    # {10: 'hello', 2: 123.45, 'knackered': 'tired'}
    print(anything[10]) # hello
    # hello
    del anything[10]
    # {2: 123.45, 'knackered': 'tired'}
    result = anything.get(10)
    # None
  • Comaring lists: same values, same order, True, same values, not same order, True.
  • Looping through lists:
    list = ['item1', 'item2']
    for item in list:
  • Random library:
    import random
    fortunes = ['You will have very good luck today.',
                'A secret admirer will soon show how they feel.',
                "The more you give, the more you'll have.",
                'Hard work pays off.',
                "Don't give up."]
    fortune = random.choice(fortunes)
  • Ranges:
    # From 0 to 9
    for i in range(10):
        print('\t' + str(random.randint(1, 1000)))
    for i in range(2005, 2016, 2):
  • Looping through dictionaries:
    dictionary = {'key1': 1, 'key2': 2}
    for item in dictionary:
    # key1
    # key2
    for key, value in dictionary.items():
        print(key, ': $', format(value, '.2f'), sep='')
    # key1: $1.00
    # key2: $2.00
  • Accessing keys and values:
    # dict_keys(['key2', 'key1'])
    # dict_values([2, 1])
  • While loop:
    x = 1
    while x != 3:
        print('x is', x)
        x = x + 1
    # x is 1
    # x is 2
  • Standard input:
    menu   = {'spam': 1, 'more spam': 2}
    orders = []
    order  = input('Type your order: ')
    while (order.upper() != 'Q'):
        found = menu.get(order)
        if found:
        order = input('Another? (q to quit): ')
  • Functions and scope:
    def average(prices):
        total = 0
        for price in prices:
            total += price
        return total/len(prices)
    def main():
        prices = [29, 21, 55, 10]
        # print(global_but_out_of_main)
    global_var = 'foo'
    global_but_out_of_main = 'bar'
    # Also, Python doesn't like empty functions
    # but it provides a placeholder (pass):
    def empty_function():
  • Files:
    # 'w' write, 'r' read, 'a' append
    sales_log = open('spam_orders.txt', 'w')
    sales_log = open('spam_orders.txt', 'r')
  • You can also handle files line by line:
    sales_log = open('', 'r')
    # Print all
    sales_log = open('', 'r')
    for line in sales_log:
  • Pattern matching (kind of):
    foo = 'hey - bye'
    (first, last) = foo.split(' - ')
    print(first, last)
  • Exceptions:
    price = input('Enter a word: ')
        price = float(price)
        print('Price =', price)
    except ValueError as err:
        print('Not a number!')
  • Classes:
    class Foo:
      def __init__(self, name):
 = name
      def hi():
    foo = Foo('bar')
  • Items in arrays always have a comma including the last one.
  • Methods inside a class are always called with self. and passed self as first arg.

And that's all I got! There is also the official tutorial in Ptython's website, and Lear X in Y min, which, as this post, works pretty much like a cheatsheet. Another recent discovery is The Hitchhiker’s Guide to Python!.

Where do I go next?

Next, you may be interested in virtual environments in Python or my Django cheatsheet. I hope they are useful!