Python is an interpreted language, meaning the code is run line by line by an interpreter. This lets us run code interactively, one line at a time. It lets you tinker, figure out what works, and perform exploratory analysis.
Full programs can also be run all at once, but we won't do that for now.
The IPython notebook runs one cell at a time. You can put as much as you want in one cell, and variables will carry over from cell to cell.
You can use Markdown to format Markdown cells, and use dollar signs to typeset LaTeX equations, such as: xn+1=f(xn)
This is the way every programming tutorial starts. In Python, it couldn't be easier.
print "Hello, world!"
Hello, world!
# Comments are specified with the # sign
'''
Longer comments can be between
triple quotes or quotation marks, like this!
'''
"""
Or like this.
"""
print "Hello, world!"
Hello, world!
Variables in Python are untyped, and don't need to be declared.
a = 3
print a
3
a = "test"
print a
test
print 2 * 3
6
a = 3
print a * 2
6
a += 1 # Increment a
print a
4
a = "na"
# String concatenation
a * 6 + "Batman!"
'nanananananaBatman!'
CAUTION: Even though variables are not typed when they are declared, they do have a type. When you divide an integer by an integer, you get an integer by default. You get around it by explicitly specifying that you want to deal with floating points
a = 3
print a/2
1
print a/2.0
1.5
Python is unique in that it uses whitespace indentation the way other languages use brackets. You can use either tabs or spaces, but you can't mix them. Four spaces is the traditional size. Lines indented by the same amount are considered to be a block.
With syntax that spans multiple blocks (e.g. if... elif... else), the commands are aligned by their indentation level.
a = 3
if a == 3:
print a
print "\n" # Empty line
for i in range(4):
print i
print "\n" # Empty line
while a < 7:
print a
a += 1
print "\n" # Empty line
if a < 7:
print "You shouldn't be here"
elif a > 100:
print "you shouldn't be here either"
else:
print "a > 7"
if False: # True is a reserved boolean value
pass # You may not have empty blocks, so use 'pass' instead.
else:
print "Printing from inside a nexted if-else"
3 0 1 2 3 3 4 5 6 a > 7 Printing from inside a nexted if-else
# Basic variables
a = 2 # int
b = 2.0 # float
c = "test" # string
print 5/a
print 5/b
2 2.5
A list is a way of storing a bunch of ordered values. They're similar to arrays in other languages, but can be extended indefinitely. Lists are indicated by square brackets.
l = [1, 2, 3]
print l
[1, 2, 3]
# You add items to a list by appending
l.append(4)
advanced note: lists in Python are technically instances of a built-in class, so you're actually accessing their methods. If you don't know what this means, don't worry about it.
# Lists can store all different kinds of data types
l.append(5.0)
l.append("six")
print l
[1, 2, 3, 4, 5.0, 'six']
List elements are accessed by indices in square brackets. You can access a single value, or a range.
l[0] # Lists count from zero
1
l[5]
'six'
l[-1] # negative numbers count from the end of the list.
'six'
l[1:3]
[2, 3]
l[:3]
[1, 2, 3]
l[3:]
[4, 5.0, 'six']
for loops in Python are really for-each, so you can use them to iterate over all elements of a list.
for i in l:
print i
1 2 3 4 5.0 six
for i in l:
if i < 5:
print i
1 2 3 4
# List operations are not element-wise
[1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
[1, 2, 3] * [4, 5, 6]
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-27-d887113b4d36> in <module>() ----> 1 [1, 2, 3] * [4, 5, 6] TypeError: can't multiply sequence by non-int of type 'list'
A list can store other lists inside of it; this is how you can build matrices.
diag = [ [1,0,0], [0,1,0], [0,0,1]]
print diag[0][1]
0
One of Python's killer features. Define a list based on another list.
first_list = [1, 2, 3, 4]
double_list = [x*2 for x in first_list]
print double_list
[2, 4, 6, 8]
Dictionaries are Python's native implementation of hashmaps / hash tables. They associate a key with a value. Keys must be unique and immutable, but values can be anything.
d = {1: 'one', 2: 'two', 3: 'three'}
d[1]
'one'
for key in d:
print key, d[key]
1 one 2 two 3 three
d[0] = 'zero'
d['nine'] = 9
d.keys() # Get all the keys
[0, 1, 2, 3, 'nine']
d.values()
['zero', 'one', 'two', 'three', 9]
d.items() # Get all the key-value pairs
[(0, 'zero'), (1, 'one'), (2, 'two'), (3, 'three'), ('nine', 9)]
functions are defined using the def keyword, as follows:
def addition(a, b):
'''
Addition function.
By convention, function documentation goes
at the top of a function in a multi-line comment
like this.
Args:
a, b are the function's arguments.
'''
c = a + b
return c # The value to return
print addition(1, 4)
5
Function arguments can also have default values, which they take on if the user doesn't provide an argument.
def operation(a, b, op="addition"):
'''
Execute a given operation.
If no operation is specified, default to 'addition'
'''
if op == "addition":
return a + b
elif op == "subtraction":
return a - b
else:
print "Unknown operation!"
Python comes with an extensive standard library. Other packages can be installed from the internet. Most need either easy_install or pip. Some are more complicated, but usually come with good documentation.
import random # the default random number library
random.randrange(9) # Access a function inside the library.
5
# You can also alias your imports for easier access:
import random as r
r.randrange(9)
2