Python Interpreter

The easiest way to get up to speed with Python is by using the command line interpreter. It throws back to you whatever you throw at it.

Like so...


$ python        ## Run the Python interpreter
Python 3.4.3 (v3.4.3:9b73f1c3e601, February 24 2015)
[MSC v.1600 Intel on win32] on wolf359
Type "help", "copyright", "credits" or "license" for more information.
>>> combs = []
>>> for x in [1, 2, 3]:
...   for y in [3, 1, 4]:
...     if x != y:
...       combs.append(x, y)
...
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

Squares


>>> squares = []
>>> for x in range(10):
...   squares.append(x**2)
...   print(squares)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

This can be shortened into an even simpler statement: known as list
comprehensions. We'll be discussing this in more detail later.


squares = [x**2 for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

One of my favorite interpreter activities...


>>> matrix = [
...     [1, 2, 3, 4],
...     [5, 6, 7, 8],
...     [9, 10, 11, 12],
... ]
...
>>> transposed = []
>>> for i in range(4):
...   transposed.append([row[i] for row in matrix])
...
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

# or even simpler
>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

Are you starting to love Python?

Craig Derington

Espousing the virtues of Secular Humanism, Libertarianism, Free and Open Source Software, Linux, Ubuntu, Terminal Multiplexing, Docker, Python, Flask, Django, Go, MySQL, PostgreSQL, MongoDB and Git.

comments powered by Disqus