This notebook gives the basics of Python 3.
The best resource for beginners is The Python Tutorial.
You can quickly do lots of things in Python, such as manipulate an image.
Excellent packages exist for almost anything reasonable a computer can do.
# You need to install Pillow for this first: conda install -c anaconda pillow
import urllib.request
import io
import PIL.Image
URL = 'http://www.gmit.ie/sites/all/themes/gmitpublic/images/gmit_logo.png'
with urllib.request.urlopen(URL) as url:
imagefile = io.BytesIO(url.read())
image = PIL.Image.open(imagefile)
imagebw = image.convert('L')
display(image, imagebw)
Many plotting packages exist, such as matplotlib.
%matplotlib inline
import numpy as np
import matplotlib.pyplot as pl
x1 = np.linspace(0, 4 * np.pi, 1000)
y1 = np.sin(x1)
y2 = np.cos(x1)
x2 = np.linspace(0, 4 * np.pi, 9)
y3 = np.sin(x2)
y4 = np.cos(x2)
pl.plot(x1, y1)
pl.plot(x2, y3, 'r.')
pl.plot(x1, y2, 'g')
pl.plot(x2, y4, 'k.')
pl.show()
Python is an excellent choice for data analytics.
%matplotlib inline
import numpy as np
import matplotlib.pyplot as pl
pl.hist(np.random.normal(10, 2, 1000))
pl.show()
One reason Python is popular is because of its philosophy.
There's an Easter egg you can find as follows.
import this
Python uses the offside rule instead of curly braces and semi-colons.
Its purpose is to improve the readability of code.
# This section of code
# does
#### absolutely nothing.
print(1) # Print the number 1.
Python doesn't require the declaration of variables or their type.
You can just start using a new variable, and Python won't complain.
Whole number literals, like 123
, are of type int.
i = 123
i
You can assign two or more variables at once using commas.
m, n = 10, 11
print(m, n)
So, you can do this:
a = 1
b = 2
print(a, b)
a, b = b, a
print(a, b)
You can check the type of a variable using the built-in type function.
type(i)
Placing a full stop, followed by optional digits, creates a float
instead.
f = 3.0
g = f / 2.0
print(f, g)
Strings can be enclosed in either double or single quotes.
The characters can be indexed as usual.
You can also access slices of strings using colons.
s = "Hello, world!"
print(s[0])
print(s[7:12])
Lists are created using square brackets and commas.
There is a related concept called tuples - they are immutable.
They can be indexed in the same way as strings, even with negative indices!
x = [1,3,4,"cow"]
t = (1,2,3,4)
print(x[2])
print(x[-1])
print(x)
print(t)
Note that it's really the commas that matter.
Here's a tuple without brackets.
v = 1,2,3
v
if 2 == 1 + 1:
print("Yes")
Here's the whole shebang.
s = "Hello, world!"
if s[0] == "H":
print("H is first letter")
elif s[1] == "e":
print("e is second letter")
else:
print("H is not first letter and e is not second letter")
You can write shorthand if statements on a single line as follows.
The if
comes after the value to return if the condition is true.
i = 3
j = 4 if i == 3 else 0
print(i, j)
for i in [1,2,3]:
print(i**2)
If you want to loop over an integer you can use the built-in range
function.
With one argument it returns the integer values from 0, including 0, up to, but not including, that number.
for i in range(10):
print(i**2)
You can create inline lists also, using an inline for loop.
squares = [i**2 for i in range(10)]
squares
Here's an example of using a loop and a conditional together.
for i in range(10):
if i % 2 == 0:
continue
elif i == 7:
break
else:
print(i)
def f(x):
return x**2 - (2 * x) + 1
for i in range(10):
print(i, f(i))
In Python, you can define one-line (anonymous) functions (that you can give a name if you want).
g = lambda x: x**3 - 10 * x**2 + x + 5
[g(i) for i in range(10)]
Python can automatically generate documentation for your code if you include docstrings. They come in triple quotes just inside your function and should describe the function.
def gcd(a, b):
"""Calculate the Greatest Common Divisor of the integers a and b."""
while b:
# a % b is a modulo b.
a, b = b, (a % b)
return a
gcd(-100, 60)
s1 = "Hello, world!"
s2 = 'Goodbye, computer!'
print(s1) # Print s1
print(s1[7]) # Print the 8th characters of s1
print(s1[7:12]) # Print characters 7 to 11 of s1
print(len(s1)) # Print the length of s1
print(s2[::2]) # Print what?
print(s2[::-1]) # Print what?