This is a collection of various statements, features, etc. of IPython and the Python language. Much of this content is taken from other notebooks so I can't take credit for it, I just extracted the highlights I felt were most useful.
Code cells are run by pressing shift-enter or using the play button in the toolbar.
a = 10
print(a)
10
import math
x = math.cos(2 * math.pi)
print(x)
1.0
Import the whole module into the current namespace instead.
from math import *
x = cos(2 * pi)
print(x)
1.0
Several ways to look at documentation for a module.
print(dir(math))
['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
help(math.cos)
Help on built-in function cos in module math: cos(...) cos(x) Return the cosine of x (measured in radians).
x = 1.0
type(x)
float
# dynamically typed
x = 1
type(x)
int
1 + 2, 1 - 2, 1 * 2, 1 / 2
(3, -1, 2, 0)
# integer division of float numbers
3.0 // 2.0
1.0
# power operator
2 ** 2
4
True and False
False
not False
True
True or False
True
2 > 1, 2 < 1, 2 > 2, 2 < 2, 2 >= 2, 2 <= 2
(True, False, False, False, True, True)
# equality
[1,2] == [1,2]
True
s = "Hello world"
type(s)
str
len(s)
11
s2 = s.replace("world", "test")
print(s2)
Hello test
s[0]
'H'
s[0:5]
'Hello'
s[6:]
'world'
s[:]
'Hello world'
# define step size of 2
s[::2]
'Hlowrd'
# automatically adds a space
print("str1", "str2", "str3")
('str1', 'str2', 'str3')
# C-style formatting
print("value = %f" % 1.0)
value = 1.000000
# alternative, more intuitive way of formatting a string
s3 = 'value1 = {0}, value2 = {1}'.format(3.1415, 1.5)
print(s3)
value1 = 3.1415, value2 = 1.5
l = [1,2,3,4]
print(type(l))
print(l)
<type 'list'> [1, 2, 3, 4]
print(l[1:3])
print(l[::2])
[2, 3] [1, 3]
l[0]
1
# don't have to be the same type
l = [1, 'a', 1.0, 1-1j]
print(l)
[1, 'a', 1.0, (1-1j)]
start = 10
stop = 30
step = 2
range(start, stop, step)
# consume the iterator created by range
list(range(start, stop, step))
[10, 12, 14, 16, 18, 20, 22, 24, 26, 28]
# create a new empty list
l = []
# add an elements using `append`
l.append("A")
l.append("d")
l.append("d")
print(l)
['A', 'd', 'd']
l[1:3] = ["b", "c"]
print(l)
['A', 'b', 'c']
l.insert(0, "i")
l.insert(1, "n")
l.insert(2, "s")
l.insert(3, "e")
l.insert(4, "r")
l.insert(5, "t")
print(l)
['i', 'n', 's', 'e', 'r', 't', 'A', 'b', 'c']
l.remove("A")
print(l)
['i', 'n', 's', 'e', 'r', 't', 'b', 'c']
del l[7]
del l[6]
print(l)
['i', 'n', 's', 'e', 'r', 't']
point = (10, 20)
print(point, type(point))
((10, 20), <type 'tuple'>)
# unpacking
x, y = point
print("x =", x)
print("y =", y)
('x =', 10) ('y =', 20)
params = {"parameter1" : 1.0,
"parameter2" : 2.0,
"parameter3" : 3.0,}
print(type(params))
print(params)
<type 'dict'> {'parameter1': 1.0, 'parameter3': 3.0, 'parameter2': 2.0}
params["parameter1"] = "A"
params["parameter2"] = "B"
# add a new entry
params["parameter4"] = "D"
print("parameter1 = " + str(params["parameter1"]))
print("parameter2 = " + str(params["parameter2"]))
print("parameter3 = " + str(params["parameter3"]))
print("parameter4 = " + str(params["parameter4"]))
parameter1 = A parameter2 = B parameter3 = 3.0 parameter4 = D
statement1 = False
statement2 = False
if statement1:
print("statement1 is True")
elif statement2:
print("statement2 is True")
else:
print("statement1 and statement2 are False")
statement1 and statement2 are False
for x in range(4):
print(x)
0 1 2 3
for word in ["scientific", "computing", "with", "python"]:
print(word)
scientific computing with python
for key, value in params.items():
print(key + " = " + str(value))
parameter4 = D parameter1 = A parameter3 = 3.0 parameter2 = B
for idx, x in enumerate(range(-3,3)):
print(idx, x)
(0, -3) (1, -2) (2, -1) (3, 0) (4, 1) (5, 2)
l1 = [x**2 for x in range(0,5)]
print(l1)
[0, 1, 4, 9, 16]
i = 0
while i < 5:
print(i)
i = i + 1
print("done")
0 1 2 3 4 done
# include a docstring
def func(s):
"""
Print a string 's' and tell how many characters it has
"""
print(s + " has " + str(len(s)) + " characters")
help(func)
Help on function func in module __main__: func(s) Print a string 's' and tell how many characters it has
func("test")
test has 4 characters
def square(x):
return x ** 2
square(5)
25
# multiple return values
def powers(x):
return x ** 2, x ** 3, x ** 4
powers(5)
(25, 125, 625)
x2, x3, x4 = powers(5)
print(x3)
125
f1 = lambda x: x**2
f1(5)
25
map(lambda x: x**2, range(-3,4))
[9, 4, 1, 0, 1, 4, 9]
# convert iterator to list
list(map(lambda x: x**2, range(-3,4)))
[9, 4, 1, 0, 1, 4, 9]
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def translate(self, dx, dy):
self.x += dx
self.y += dy
def __str__(self):
return("Point at [%f, %f]" % (self.x, self.y))
p1 = Point(0, 0)
print(p1)
Point at [0.000000, 0.000000]
p2 = Point(1, 1)
p1.translate(0.25, 1.5)
print(p1)
print(p2)
Point at [0.250000, 1.500000] Point at [1.000000, 1.000000]
try:
print(test)
except:
print("Caught an expection")
Caught an expection
try:
print(test)
except Exception as e:
print("Caught an exception: " + str(e))
Caught an exception: name 'test' is not defined