KEMBAR78
Intro to Python (High School) Unit #3 | PPTX
<High School>
Computer Science:
Introduction to Python
Unit #3
(Covering CPython 3)
Spring 2017
License: CC BY-SA 4.0 (except images), by Jay Coskey 1
Unit #3
GUI Programming
2
GUI Programming
3
• Turtle graphics
• GUI programming with tkinter
• Data Visualization (in 2D) with matplotlib and Jupyter
turtle graphics
4
Turtle graphics — Introduction
This demo can give you an idea of what turtle graphics in Python is like. Explore!
python –m turtledemo # Take a look at the "Examples" menu
python –m turtledemo.clock
5License: CC BY-SA 4.0 (except images), by Jay Coskey
Turtle graphics dates back to
Seymour Papert (1928-2016)
who, in the '60s, added it to
an educational programming
language called Logo, which
he & a few others designed.
It involved moving a virtual
pen-holding turle that left
visible paths on the screen.
Turtle graphics — Source code
Importing "turtle" gives you access to classes such as Screen, Turtle, and many others.
Here is how to draw a square (which is a polygon with four sides).
6License: CC BY-SA 4.0 (except images), by Jay Coskey
import turtle
def forward_right(t, fval, rval):
t.forward(fval)
t.right(rval)
screen = turtle.Screen()
t = turtle.Turtle()
t.setheading(90) # Start facing ↑
for k in range(0, 4):
forward_right(t, 50, 90)
screen.mainloop()
Turtle graphics — Round things
If you draw a polygon with far more sides, the result looks more circle-ish.
7License: CC BY-SA 4.0 (except images), by Jay Coskey
import turtle
def forward_right(t, fval, rval):
t.forward(fval)
t.right(rval)
screen = turtle.Screen()
t = turtle.Turtle()
t.setheading(90)
NUM_SIDES = 12
for k in range(0, NUM_SIDES):
forward_right(t, 50, 360/NUM_SIDES)
screen.mainloop()
Start & end point
Turtle graphics — Pointy things
By switching from small jumps and small angle changes to large jumps and large angle changes,
the shapes generated become pointy.
8License: CC BY-SA 4.0 (except images), by Jay Coskey
import turtle
def forward_right(t, fval, rval):
t.forward(fval)
t.right(rval)
screen = turtle.Screen()
t = turtle.Turtle()
t.setheading(90)
POINTS = 12
for k in range(0, POINTS):
rval = (360/POINTS) * ((POINTS/2) – 1)
forward_right(t, 200, rval)
screen.mainloop() Start & end point
Turtle graphics — Wavy things
Changing the angle over time in a more complex way can generate more interesting shapes.
9License: CC BY-SA 4.0 (except images), by Jay Coskey
import turtle
def forward_right(t, fval, rval):
t.forward(fval)
t.right(rval)
def sine_ish(k):
return 45
+ 90 * math.sin(math.pi*k / 25)
screen = turtle.Screen()
t = turtle.Turtle()
t.setheading(90)
For k in range(0, 200):
forward_right(t, 30, sine_ish(k))
screen.mainloop()
Start & end point
Turtle graphics — Fractal things
Recursion can be used to generate fractals — shapes that are self-similar at different scales.
10License: CC BY-SA 4.0 (except images), by Jay Coskey
import turtle
def forward_right(t, fval, rval):
fractal(t, fval, 3, 1)
t.right(rval)
def fractal(t, dist, depth, dir):
# def from the fractalcurves demo
window = turtle.Screen()
t = turtle.Turtle()
t.setheading(0)
for k in range(0, 3):
forward_right(t, 150, 120)
window.mainloop()
Start & end point
This shape is known as
a "Koch snowflake",
after Helge von Koch
(1870-1924)
Turtle graphics — Pen width, color, up/down
• Let's revise the script square.py to make it more colorful.
License: CC BY-SA 4.0 (except images), by Jay Coskey 11
import random
import turtle
def forward_right(t, pcol, pwidth, fval, rval):
t.color(pcol)
t.width(pwidth)
for k in range(0, 10): # Break edge into 10 parts
d = random.randint(3, 7)
t.pendown()
t.forward(d * fval / 100)
t.penup()
t.forward((10 – d) * fval / 100)
t.right(rval)
if __name__ == '__main__':
(window, t) = (turtle.Screen(), turtle.Turtle())
t.setheading(90)
forward_right(t, 'red', 3, fval=400, rval=90)
forward_right(t, 'green', 6, fval=400, rval=90)
forward_right(t, 'blue', 9, fval=400, rval=90)
forward_right(t, 'black',12, fval=400, rval=90)
window.mainloop() Start & end point
Turtle graphics — absolute coordinates (2)
• Absolute coordinates can be used in pong-type games.
License: CC BY-SA 4.0 (except images), by Jay Coskey 12
import turtle
...
(wn, t) = (turtle.Screen(), turtle.Turtle())
...
while True:
if x < left_wall or x > right_wall:
dx = - dx
if y < bottom_wall or y > top_wall:
dy = - dy
x += dx
y += dy
t.goto(x, y)
Turtle graphics — absolute coordinates
• Turtle understands not only forward/back/left/right, but also goto.
License: CC BY-SA 4.0 (except images), by Jay Coskey 13
import turtle
def draw_line(t, x1, y1, x2, y2):
t.penup()
t.goto(x1, y1) # Starting point of line segment
t.pendown()
t.goto(x2, y2) # Ending point of line segment
if __name__ == '__main__':
(window, t) = (turtle.Screen(), turtle.Turtle())
t.hideturtle() # Don't show the turtle
t.speed(0) # Fastest; no delay between drawing
SCALE = 75
# Draw horizontal lines
draw_line(t, -3*SCALE, -SCALE, +3*SCALE, -SCALE)
draw_line(t, -3*SCALE, +SCALE, +3*SCALE, +SCALE)
# Draw vertical lines
draw_line(t, -SCALE, -3*SCALE, -SCALE, +3*SCALE)
draw_line(t, +SCALE, -3*SCALE, +SCALE, +3*SCALE)
window.mainloop()
goto sets the absolute coordinates of of the turtle.
The function setheading sets the absolute
direction. By default, it's measured in degrees.
Other related functions:
position (reads x & y); setx & sety (sets them)
heading (gets the current value of heading)
Turtle graphics — coloring by numbers
• Colors can be set by specifying values for red, green, and blue (r, g, b).
License: CC BY-SA 4.0 (except images), by Jay Coskey 14
import math
import turtle
def draw_arc(t, center, radius,
from_angle, to_angle, steps):
<...This uses penup, pendown, and goto...>
<...See the script, rainbow.py...>
(screen, t) = (turtle.Screen(), turtle.Turtle())
screen.delay(0) # Draw as fast as possible
angle_min = 10; angle_max = 170
arc_steps = 100
radius_min = 100; radius_max = 200; radius_steps = 300
screen.colormode(1.0) # Use values from 0 to 1.0.
for k in range(0, radius_steps + 1):
radius = radius_min + k*(radius_max-radius_min)/radius_steps
red = max(0, -1 + 2 * k / radius_steps) # 0-0-1
green = max(0, 1 - math.fabs(k - 128)/128) # 0-1-0
blue = max(0, 1 - 2 * k / radius_steps) # 1-0-0
t.color(red, green, blue)
draw_arc(t, (0, 0), radius, 30, 150, arc_steps)
screen.mainloop()
If you can produce a formula to
determine the coordinates of a curve,
then you can use goto to draw it.
For example, a circle can be drawn
using trigonometry:
x(t) = math.cos(t)
y(t) = math.sin(t)
You don't need to define your own
draw_arc function. Turtle provides a
similar function called circle, and
related functions begin_fill and
end_fill.
turtle graphics — events & actions
• Keyboard clicks and mouse clicks are examples of (software) events.
• Functions like onkey and onscreenclick register functions that are called
when certain events happen.
• Functions that don't return a value are sometimes called actions.
License: CC BY-SA 4.0 (except images), by Jay Coskey 15
Event
Keyboard click
Mouse click
Alarm clock going off
Action
Change turtle speed/direction
More turtle position
Change turtle color
Move game paddle
Turtle graphics — keyboard interactivity
The turtle "screen" ("window") used in turtle graphics can be set up to respond to keystrokes (or mouse clicks).
And it can handle more than one turtle at a time. Sounds like the beginning of a game….
16License: CC BY-SA 4.0 (except images), by Jay Coskey
import turtle
ANGLE=30; DISTANCE=25
def go_forward(t): t.foward(DISTANCE)
def go_left(t): t.left(ANGLE)
def go_right(t): t.right(ANGLE)
def go_back(t): t.back(DISTANCE)
def setup_keys(window, t,
up, left, right, down):
window.onkey(lambda: go_forward(t), up)
window.onkey(lambda: go_left(t), left)
window.onkey(lambda: go_right(t), right)
window.onkey(lambda: go_back(t), back)
window = turtle.Screen()
(t1, t2) = (turtle.Turtle(), turtle.Turtle())
# Set turtle colors
setup_keys(window, t1, 'e', 's', 'f', 'd')
setup_keys(window, t2, 'Up','Left','Right','Down')
window.listen()
window.mainloop()
t.shape(shapename) sets the shape of
the turtle: arrow, turtle, circle, square,
triangle, classic, or one of your own shapes.
t.color(pen_color, fill_color)
sets the color of the pen/path, and the color
of the turtle. They can also be set separately.
Also see the turtle demo "two_canvases".
Turtle graphics — mouse interactivity
The turtle Screen can also respond to mouse clicks… but it might be better to use tkinter for this.
17License: CC BY-SA 4.0 (except images), by Jay Coskey
# Partial script
import math
import turtle
(tgt_x, tgt_y) = (100, 0)
def set_tgt_coords(x, y):
global tgt_x # Use the variables tgt_x, tgt_y defined above.
global tgt_y
(tgt_x, tgt_y) = (x, y)
(wn, t) = (turtle.Screen(), turtle.Turtle())
wn.onscreenclick(set_tgt_coords)
wn.listen()
while True:
speed = 1
move_turtle_toward_target(t, speed) # Code not shown here
Turtle graphics — Conclusion
This is a tiny portion of what can be done with turtle graphics. It also supports the
addition of text, using a "fill color", etc. Don't forget about the turtledemo module!
18License: CC BY-SA 4.0 (except images), by Jay Coskey
Round things
Pointy things
Your things
Insert
your
masterpiece
here
Fractal thingsWavy things
GUI programming with tkinter
19
tkinter & turtle (1)
• Turtle programs create a new window to
display their graphics.
• How do they do this? They use a Python
package called tkinter, which focuses on the
handling of windows and their contents.
License: CC BY-SA 4.0 (except images), by Jay Coskey 20
• tkinter is based on an earlier "widget toolkit" called Tk, which was first
released in 1991, by John Ousterhout.
• Fun (?) fact: John Ousterhout was the 1987 winner of the Grace Murray Hopper award.
• The first winner of this award, in 1971, was Donald E. Knuth.
• The 1979 winner was Steve "Woz" Wozniak, who co-founded Apple with Steve Jobs.
• The 1993 winner was Bjarne Stroustrup, who invented the C++ programming language.
tkinter & turtle (2)
• Here is an example of a
very simple app that uses
both tkinter and turtle.
License: CC BY-SA 4.0 (except images), by Jay Coskey 21
tkinter & turtle (3)
• Tkinter/turtle apps can also
interact with resources on
your computer, or with
others over the internet .
• There are modules available
for everything. If you can
imagine it, there's some way
to do it.
License: CC BY-SA 4.0 (except images), by Jay Coskey 22
###############
#S# # #
# # ### ### # #
# # # # # #
# ### # ### # #
# # # # #
# ### ### # #
# # # ### #
# # ### # # # #
# # # # # # #
# # # # # # #
# # # # ##### #
# # #F #
###############
Tkinter — Hello, world!
# From docs.python.org/3/library/Tkinter.html
import tkinter as tk
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.pack()
self.create_widgets()
def create_widgets(self):
self.hi_there = tk.Button(self)
self.hi_there["text"] = "Hello Worldn(click me)"
self.hi_there["command"] = self.say_hi
self.hi_there.pack(side="top")
self.quit = tk.Button(self, text="QUIT", fg="red",
command=root.destroy)
self.quit.pack(side="bottom")
def say_hi(self):
print("hi there, everyone!")
root = tk.Tk()
app = Application(master=root)
app.mainloop()
License: CC BY-SA 4.0 (except images), by Jay Coskey 23
Place the "hi_there" button in its parent "frame".
Put all the quit button info in this one statement.
Create a button. Set the button's text.
Loop forever, listening for button clicks. Without this, the program quickly exits.
Set the function to be executed on button click.
Create and initialie the application window.
Place the quit button in its parent "Frame".
Create the application window or "frame".
tkinter layout/geometry managers
• The last example had few controls. Richer user experiences are more complex.
• tkinter provides three ways of controlling the location of the widgets.
• place — This Layout Manager is toooo complicated (for most "use cases")
• This requires you to specify the coordinates of each widget being placed. And it doesn't carry over
well to the event when a window is resized by the user. It'll drive you nuts.
• pack — This Layout Manager is toooo simple (for some "use cases")
• This works by declaring for each widget which side(s) of the containing frame it's pushed up against
(top, bottom, left, and right). This can work for some layouts, but when you want to do something
that involves two sides at once (e.g., having two scroll bars meet in the lower-right corner, but
leave a blank space, you'll wish you had chosen grid.
• grid — This Layout Manager is juuuust right
• You specify a 2-D grid of cells, and declare which widgets lie in which cells. (Think checkers/chess.)
Note: Some widgets (e.g., Frame) can contain other widgets, which can contain others.
This allows for more complicated layouts (e.g., a Monopoly board).
License: CC BY-SA 4.0 (except images), by Jay Coskey 24
A simple Tkinter layout
License: CC BY-SA 4.0 (except images), by Jay Coskey 25
Chatterbox — □ X
Menubar reserved for menus
"Dashboard area", for the display
the current state of the program.
"Control area", for changing
the state of the program.
Any layout manager can work here, but as
the user experience gets more complex,
some layout managers become easier to
use than others….
Erik> Wassup?
Update
Available Tkinter controls/widgets
License: CC BY-SA 4.0 (except images), by Jay Coskey 26
File | Edit |
Chat name: Thorvald Asvaldsson
Connected as:
Send
Message: Not much. Just trying to stay warm.
Thorvald Asvaldsson
Chatterbox — □ X
Disconnect
○ Broadcast to all
● Send to individual
Send to: Erik
Menubar with two menus
Label and (text) Entry controls
Text control
Scrollbar control
Lable, Entry, and Button controls
Radiobutton, Label, "Dropdown"
Button
For more info, see https://docs.python.org/3/library/tk.html and http://tkinter.unpythonic.net/wiki/
and https://docs.python.org/3/library/tkinter.ttk.html
tkinter widgets!
• tkinter has many controls/widgets available to build a GUI with.
License: CC BY-SA 4.0 (except images), by Jay Coskey 27
Canvas
Checkbutton
Frame
(text) Entry
Button
Label
Listbox
Message
Menubutton
Menu
Text
Scrollbar Scale
Radiobutton
LabelFrame
Toplevel
Spinbox
PanedWindow
tkinter.ttk — More widgets!
• If you're going to use tkinter for your Course Project, check out some
of these other widgets that are available outside of tkinter.
from tkinter import ttk
ttk widgets available:
Combobox
Notebook
Progressbar
Separator
Sizegrip
Treeview
License: CC BY-SA 4.0 (except images), by Jay Coskey 28
Note: tkinter.ttk replaces an
older module called tkinter.tix.
Other desktop GUI options
• Again, tkinter is based on the widget toolkit Tk, which was first released in 1991.
• Tkinter has long come bundled with Python. But there are other GUI packages available.
• Kivy (multi-touch-enabled media rich apps; successor to the PyMT project; MIT license)
• Written (from scratch?) by the Kivy foundation; first released in 2011
• Libavg
• Based on OpenGL, which was first released in 1992
• PyGi
• Based on the GNOME platform, first released in 1999
• PyQt (GPL license) and PySide (LGPL license)
• Based on the Qt toolkit, first released in 1995
• wxPython and gui2Py (which is based on wxPython)
• Based on wxWidgets, which was first released in 1992
License: CC BY-SA 4.0 (except images), by Jay Coskey 29
Data Visualization (in 2D)
with matplotlib and Jupyter
30
"ReachOne" step count visualization
# See Question 2(b) on HW #4.
import matplotlib.pyplot as plt
def reachone_next(n: int) -> int:
result = n / 2 if n % 2 == 0 else 3 * n + 1
return result
def reachone_count(n: int) -> int:
count = 0
while n > 1:
count += 1
n = reachone_next(n)
return count
xs = range(1,10001)
ys = [reachone_count(x) for x in xs]
plt.scatter(xs, ys)
plt.show()
License: CC BY-SA 4.0 (except images), by Jay Coskey 31
Look — a pattern! One that
would not have become
apparent, except through
such a visualization.
Palindrome step count visualization (1)
def is_palindrome(n):
return str(n) == str(n)[::-1]
def reachpalindrome_next(n):
return n + int(str(n)[::-1])
def reachpalindrome_step_count(n):
count = 0
while not is_palindrome(n):
count += 1
n = reachpalindrome_next(n)
return count
License: CC BY-SA 4.0 (except images), by Jay Coskey
32
Let's try something similar, but
• Have the "step" be reversing the digits of a number and adding the reversed number to the original
• Repeat until the result is a palindrom, and count the number of steps until that happens.
If we use the number 176 as
an example, it takes 5 steps to
reach a palindrome.
0: 176
1: 176 + 671 = 847
2: 847 + 748 = 1595
3: 1595 + 5951 = 7546
4: 7546 + 6457 = 14003
5: 14003 + 30041 = 44044
Palindrome step count visualization (2)
import matplotlib.pyplot as plt
<... functions as on previous slide ...>
pxs = range(1,101)
pys = [reachpalindrome_step_count(px) for px in pxs]
plt.scatter(pxs, pys)
plt.title('ReachPalindrome steps')
plt.xlim(-1,101)
plt.ylim(-1,25)
plt.xlabel('Value')
plt.ylabel('Step count')
for px in pxs:
if pys[px - 1] > 10:
py = pys[px - 1]
plt.annotate('({0},{1})'.format(px,py),
xy=(px,py), xytext=(px-50,py-5-(px-89)),
arrowprops=dict(facecolor='black',shrink=0.05))
plt.show()
License: CC BY-SA 4.0 (except images), by Jay Coskey
33
The matplotlib package has support for a broad range of means of visualizations.
• We can add titles, labels, annotations, etc.
• It looks like there are patterns in this "scatterplot" that could lead to other insights….
Q: Why visualize? A: Anscomb's Quartet
• Anscombe's Quartet doesn't have any violins.
• It's four sets of 11 points each, created in 1973 by
English statistician Francis Anscombe (1918-2001).
• Each set has means (x & y coords), variances (x & y),
x-y correlations, and best-fit line as each other set.
• So if you only look at aggregated statistics, each set
looks exactly the same as all the others.
• But if you look at the scatter plots of these sets, then
they all look quite distinct.
• Moral of the story: Visualize your data to better
understand it. There might be more to the story.
License: CC BY-SA 4.0 (except images), by Jay Coskey 34
You won't come across one of the data sets in Anscombe's Quartet, but a common
occurrence is that your dataset looks like it's made up of two or more datasets
superimposed. It might make sense to break them apart and study each one separately.
What is the Mandelbrot set?
• There's a famous 2-D set in mathematics called the Mandelbrot set (Benoît Mandelbrot,
1924-2010). It's defined similarly—in terms of the number of iterations of a function.
License: CC BY-SA 4.0 (except images), by Jay Coskey
35
The idea is simple. Take a particular simple function defined
for all points on the (complex) plane. Call it f.
• For some points p near the origin, all iterations of f (i.e.,
f(p), f(f(p)), f(f(f(p))), etc. remain near the origin.
• For some other points, iterations of f quickly zoom
outward, getting further & further from the origin.
• For points inbetween, the pattern is very complex.
def mandelbrot_iter_count(x, y, iterations_max):
z = 0
c = x + 1j*y # Note: 1j = math.sqrt(-1)
iterations_until_divergence = iter_max
for k in range(1, iter_max):
z = z*z + c
if abs(z) > 2: # Divergence
iterations_until_divergence = k
break
return iterations_until_divergence
To create the Mandelbrot set, color by numbers:
• For the points on the plane that always stay
near the origin—give them one color.
• For points that quickly zoom away, give them
another color.
• For points inbetween, given them a color that
transitions from one to the other.
Mandelbrot set visualization
• I wonder if Mandelbrot liked almond bread. Anyhow, where were we?
License: CC BY-SA 4.0 (except images), by Jay Coskey
36
import matplotlib.pyplot as plt
import numpy as np
def mandelbrot_iter_counts(xmin, xmax, ymin, ymax, nx=500, ny=500, iter_max=500):
dx = (xmax-xmin) / (nx-1)
dy = (ymax-ymin) / (ny-1)
xs = [xmin + i*dx for i in range(nx)]
ys = [ymin + i*dy for i in range(ny)]
return [[mandelbrot_iter_count(x, y, iter_max) for x in xs] for y in ys]
if __name__ == '__main__':
plt.figure()
bounds_all = [-1.6, 0.6, -1.1, 1.1] # The entire set
bounds_a = [-1.0, -0.5, 0.0, 0.3] # Zoom in
bounds_b = [-0.78, -0.73, 0.02, 0.08] # More zoom
bounds_c = [-0.752, -0.749, 0.031, 0.0335] # Enhance!
(xmin, xmax, ymin, ymax) = bounds_all
(nx, ny, iter_max) = (100, 100, 100)
plt.imshow(np.array(mandelbrot_iter_counts(xmin,xmax,ymin,ymax,
nx,ny,iter_max)),
extent=(xmin,xmax,ymin,ymax), origin='lower')
plt.show()
Note: numpy is used for many high-performance computations
More data visualization with matplotlib
• We've barely scratched the surface of matplotlib.
• Check out the gallery of matplotlib visualizations at http://matplotlib.org/gallery.html
• You can click on any of these visualizations to get the underlying source code.
• There are other visualization libraries in Python, including Bokeh (http://bokeh.pydata.org/),
which focuses on interactive display. Of course, Bokeh has its own gallery.
License: CC BY-SA 4.0 (except images), by Jay Coskey
37
Jupyter (was IPython notebook) (1)
• Jupyter is a way of using Python with (distributed) interactive notebooks.
• See https://ipython.org/ipython-doc/3/interactive/ for the details.
License: CC BY-SA 4.0 (except images), by Jay Coskey 38
• Your script becomes a notebook
made of a kernel and console.
• A notebook has cells that are chunks
of code that can be edited, run, or
moved around as needed.
• This is a very handy environment,
especially for data analysis, where
there is often a linear flow of
execution involving:
• Creating a data model (e.g., weather)
• Refining & evolving the model
• Running & evaluating the model
• Outputting summary information
Jupyter (was IPython notebook) (2)
• To run Jupyter on your laptop, run the command
ipython notebook
• There are many public Jupyter notebooks over at
• http://nbviewer.jupyter.org/
License: CC BY-SA 4.0 (except images), by Jay Coskey 39
And there's even more available at github.com.
IPython notebooks (.ipynb) files checked into
github.com can be viewed as IPython notebooks.
Just search on Google for
filetype:ipynb site:github.com
Example: You can make Deep Dream images using
https://github.com/google/deepdream/blob
/master/dream.ipynb
nbviewer uses
nbconvert.
Notebooks can
be converted
to HTML, PDF,
or a regular
Python file.
Additional Resources
40
A few more Python language features
• Class inheritance and multiple inheritance:
• https://docs.python.org/3/tutorial/classes.html#inheritance
• "Context managers" (i.e., scoped resources) using "with" statements
• https://www.python.org/dev/peps/pep-0343/
• Decorators
• https://www.python.org/dev/peps/pep-0318/
• https://python-3-patterns-idioms-test.readthedocs.io/en/latest/PythonDecorators.html
• https://dbader.org/blog/python-decorators
• Exceptions (a common means of error handling)
• https://docs.python.org/3/library/exceptions.html
• Iterables, iterators, and generators
• http://www.python-course.eu/python3_generators.php
• Parameter packing and unpacking (*args and **kwargs)
• http://thepythonguru.com/python-args-and-kwargs/
• Aynchronous features (:
• https://docs.python.org/3/library/asyncio.html
• https://www.youtube.com/watch?v=M-UcUs7IMIM
License: CC BY-SA 4.0 (except images), by Jay Coskey 41
Additional resources
• CherryPy (Introduction to web development in Python)
• http://cherrypy.org/
• Python the Hard Way:
• https://learnpythonthehardway.org/book/
• Python 3 Patterns, Recipes, and Idioms
• https://media.readthedocs.org/pdf/python-3-patterns-idioms-test/latest/python-3-
patterns-idioms-test.pdf
• Python's numerical and scientific libraries
• numpy, scipy, pandas (data structures & analysis), astropy (astronomy), sympy
(symbolic mathematics), scikit-learn (AI-type library, using "machine learning")
• Machine learning (think "artificial intelligence") using Python
• http://scikit-learn.org/stable/
• Teach Yourself Programming in Ten Years
• http://norvig.com/21-days.html
License: CC BY-SA 4.0 (except images), by Jay Coskey 42

Intro to Python (High School) Unit #3

  • 1.
    <High School> Computer Science: Introductionto Python Unit #3 (Covering CPython 3) Spring 2017 License: CC BY-SA 4.0 (except images), by Jay Coskey 1
  • 2.
  • 3.
    GUI Programming 3 • Turtlegraphics • GUI programming with tkinter • Data Visualization (in 2D) with matplotlib and Jupyter
  • 4.
  • 5.
    Turtle graphics —Introduction This demo can give you an idea of what turtle graphics in Python is like. Explore! python –m turtledemo # Take a look at the "Examples" menu python –m turtledemo.clock 5License: CC BY-SA 4.0 (except images), by Jay Coskey Turtle graphics dates back to Seymour Papert (1928-2016) who, in the '60s, added it to an educational programming language called Logo, which he & a few others designed. It involved moving a virtual pen-holding turle that left visible paths on the screen.
  • 6.
    Turtle graphics —Source code Importing "turtle" gives you access to classes such as Screen, Turtle, and many others. Here is how to draw a square (which is a polygon with four sides). 6License: CC BY-SA 4.0 (except images), by Jay Coskey import turtle def forward_right(t, fval, rval): t.forward(fval) t.right(rval) screen = turtle.Screen() t = turtle.Turtle() t.setheading(90) # Start facing ↑ for k in range(0, 4): forward_right(t, 50, 90) screen.mainloop()
  • 7.
    Turtle graphics —Round things If you draw a polygon with far more sides, the result looks more circle-ish. 7License: CC BY-SA 4.0 (except images), by Jay Coskey import turtle def forward_right(t, fval, rval): t.forward(fval) t.right(rval) screen = turtle.Screen() t = turtle.Turtle() t.setheading(90) NUM_SIDES = 12 for k in range(0, NUM_SIDES): forward_right(t, 50, 360/NUM_SIDES) screen.mainloop() Start & end point
  • 8.
    Turtle graphics —Pointy things By switching from small jumps and small angle changes to large jumps and large angle changes, the shapes generated become pointy. 8License: CC BY-SA 4.0 (except images), by Jay Coskey import turtle def forward_right(t, fval, rval): t.forward(fval) t.right(rval) screen = turtle.Screen() t = turtle.Turtle() t.setheading(90) POINTS = 12 for k in range(0, POINTS): rval = (360/POINTS) * ((POINTS/2) – 1) forward_right(t, 200, rval) screen.mainloop() Start & end point
  • 9.
    Turtle graphics —Wavy things Changing the angle over time in a more complex way can generate more interesting shapes. 9License: CC BY-SA 4.0 (except images), by Jay Coskey import turtle def forward_right(t, fval, rval): t.forward(fval) t.right(rval) def sine_ish(k): return 45 + 90 * math.sin(math.pi*k / 25) screen = turtle.Screen() t = turtle.Turtle() t.setheading(90) For k in range(0, 200): forward_right(t, 30, sine_ish(k)) screen.mainloop() Start & end point
  • 10.
    Turtle graphics —Fractal things Recursion can be used to generate fractals — shapes that are self-similar at different scales. 10License: CC BY-SA 4.0 (except images), by Jay Coskey import turtle def forward_right(t, fval, rval): fractal(t, fval, 3, 1) t.right(rval) def fractal(t, dist, depth, dir): # def from the fractalcurves demo window = turtle.Screen() t = turtle.Turtle() t.setheading(0) for k in range(0, 3): forward_right(t, 150, 120) window.mainloop() Start & end point This shape is known as a "Koch snowflake", after Helge von Koch (1870-1924)
  • 11.
    Turtle graphics —Pen width, color, up/down • Let's revise the script square.py to make it more colorful. License: CC BY-SA 4.0 (except images), by Jay Coskey 11 import random import turtle def forward_right(t, pcol, pwidth, fval, rval): t.color(pcol) t.width(pwidth) for k in range(0, 10): # Break edge into 10 parts d = random.randint(3, 7) t.pendown() t.forward(d * fval / 100) t.penup() t.forward((10 – d) * fval / 100) t.right(rval) if __name__ == '__main__': (window, t) = (turtle.Screen(), turtle.Turtle()) t.setheading(90) forward_right(t, 'red', 3, fval=400, rval=90) forward_right(t, 'green', 6, fval=400, rval=90) forward_right(t, 'blue', 9, fval=400, rval=90) forward_right(t, 'black',12, fval=400, rval=90) window.mainloop() Start & end point
  • 12.
    Turtle graphics —absolute coordinates (2) • Absolute coordinates can be used in pong-type games. License: CC BY-SA 4.0 (except images), by Jay Coskey 12 import turtle ... (wn, t) = (turtle.Screen(), turtle.Turtle()) ... while True: if x < left_wall or x > right_wall: dx = - dx if y < bottom_wall or y > top_wall: dy = - dy x += dx y += dy t.goto(x, y)
  • 13.
    Turtle graphics —absolute coordinates • Turtle understands not only forward/back/left/right, but also goto. License: CC BY-SA 4.0 (except images), by Jay Coskey 13 import turtle def draw_line(t, x1, y1, x2, y2): t.penup() t.goto(x1, y1) # Starting point of line segment t.pendown() t.goto(x2, y2) # Ending point of line segment if __name__ == '__main__': (window, t) = (turtle.Screen(), turtle.Turtle()) t.hideturtle() # Don't show the turtle t.speed(0) # Fastest; no delay between drawing SCALE = 75 # Draw horizontal lines draw_line(t, -3*SCALE, -SCALE, +3*SCALE, -SCALE) draw_line(t, -3*SCALE, +SCALE, +3*SCALE, +SCALE) # Draw vertical lines draw_line(t, -SCALE, -3*SCALE, -SCALE, +3*SCALE) draw_line(t, +SCALE, -3*SCALE, +SCALE, +3*SCALE) window.mainloop() goto sets the absolute coordinates of of the turtle. The function setheading sets the absolute direction. By default, it's measured in degrees. Other related functions: position (reads x & y); setx & sety (sets them) heading (gets the current value of heading)
  • 14.
    Turtle graphics —coloring by numbers • Colors can be set by specifying values for red, green, and blue (r, g, b). License: CC BY-SA 4.0 (except images), by Jay Coskey 14 import math import turtle def draw_arc(t, center, radius, from_angle, to_angle, steps): <...This uses penup, pendown, and goto...> <...See the script, rainbow.py...> (screen, t) = (turtle.Screen(), turtle.Turtle()) screen.delay(0) # Draw as fast as possible angle_min = 10; angle_max = 170 arc_steps = 100 radius_min = 100; radius_max = 200; radius_steps = 300 screen.colormode(1.0) # Use values from 0 to 1.0. for k in range(0, radius_steps + 1): radius = radius_min + k*(radius_max-radius_min)/radius_steps red = max(0, -1 + 2 * k / radius_steps) # 0-0-1 green = max(0, 1 - math.fabs(k - 128)/128) # 0-1-0 blue = max(0, 1 - 2 * k / radius_steps) # 1-0-0 t.color(red, green, blue) draw_arc(t, (0, 0), radius, 30, 150, arc_steps) screen.mainloop() If you can produce a formula to determine the coordinates of a curve, then you can use goto to draw it. For example, a circle can be drawn using trigonometry: x(t) = math.cos(t) y(t) = math.sin(t) You don't need to define your own draw_arc function. Turtle provides a similar function called circle, and related functions begin_fill and end_fill.
  • 15.
    turtle graphics —events & actions • Keyboard clicks and mouse clicks are examples of (software) events. • Functions like onkey and onscreenclick register functions that are called when certain events happen. • Functions that don't return a value are sometimes called actions. License: CC BY-SA 4.0 (except images), by Jay Coskey 15 Event Keyboard click Mouse click Alarm clock going off Action Change turtle speed/direction More turtle position Change turtle color Move game paddle
  • 16.
    Turtle graphics —keyboard interactivity The turtle "screen" ("window") used in turtle graphics can be set up to respond to keystrokes (or mouse clicks). And it can handle more than one turtle at a time. Sounds like the beginning of a game…. 16License: CC BY-SA 4.0 (except images), by Jay Coskey import turtle ANGLE=30; DISTANCE=25 def go_forward(t): t.foward(DISTANCE) def go_left(t): t.left(ANGLE) def go_right(t): t.right(ANGLE) def go_back(t): t.back(DISTANCE) def setup_keys(window, t, up, left, right, down): window.onkey(lambda: go_forward(t), up) window.onkey(lambda: go_left(t), left) window.onkey(lambda: go_right(t), right) window.onkey(lambda: go_back(t), back) window = turtle.Screen() (t1, t2) = (turtle.Turtle(), turtle.Turtle()) # Set turtle colors setup_keys(window, t1, 'e', 's', 'f', 'd') setup_keys(window, t2, 'Up','Left','Right','Down') window.listen() window.mainloop() t.shape(shapename) sets the shape of the turtle: arrow, turtle, circle, square, triangle, classic, or one of your own shapes. t.color(pen_color, fill_color) sets the color of the pen/path, and the color of the turtle. They can also be set separately. Also see the turtle demo "two_canvases".
  • 17.
    Turtle graphics —mouse interactivity The turtle Screen can also respond to mouse clicks… but it might be better to use tkinter for this. 17License: CC BY-SA 4.0 (except images), by Jay Coskey # Partial script import math import turtle (tgt_x, tgt_y) = (100, 0) def set_tgt_coords(x, y): global tgt_x # Use the variables tgt_x, tgt_y defined above. global tgt_y (tgt_x, tgt_y) = (x, y) (wn, t) = (turtle.Screen(), turtle.Turtle()) wn.onscreenclick(set_tgt_coords) wn.listen() while True: speed = 1 move_turtle_toward_target(t, speed) # Code not shown here
  • 18.
    Turtle graphics —Conclusion This is a tiny portion of what can be done with turtle graphics. It also supports the addition of text, using a "fill color", etc. Don't forget about the turtledemo module! 18License: CC BY-SA 4.0 (except images), by Jay Coskey Round things Pointy things Your things Insert your masterpiece here Fractal thingsWavy things
  • 19.
  • 20.
    tkinter & turtle(1) • Turtle programs create a new window to display their graphics. • How do they do this? They use a Python package called tkinter, which focuses on the handling of windows and their contents. License: CC BY-SA 4.0 (except images), by Jay Coskey 20 • tkinter is based on an earlier "widget toolkit" called Tk, which was first released in 1991, by John Ousterhout. • Fun (?) fact: John Ousterhout was the 1987 winner of the Grace Murray Hopper award. • The first winner of this award, in 1971, was Donald E. Knuth. • The 1979 winner was Steve "Woz" Wozniak, who co-founded Apple with Steve Jobs. • The 1993 winner was Bjarne Stroustrup, who invented the C++ programming language.
  • 21.
    tkinter & turtle(2) • Here is an example of a very simple app that uses both tkinter and turtle. License: CC BY-SA 4.0 (except images), by Jay Coskey 21
  • 22.
    tkinter & turtle(3) • Tkinter/turtle apps can also interact with resources on your computer, or with others over the internet . • There are modules available for everything. If you can imagine it, there's some way to do it. License: CC BY-SA 4.0 (except images), by Jay Coskey 22 ############### #S# # # # # ### ### # # # # # # # # # ### # ### # # # # # # # # ### ### # # # # # ### # # # ### # # # # # # # # # # # # # # # # # # # # # # ##### # # # #F # ###############
  • 23.
    Tkinter — Hello,world! # From docs.python.org/3/library/Tkinter.html import tkinter as tk class Application(tk.Frame): def __init__(self, master=None): super().__init__(master) self.pack() self.create_widgets() def create_widgets(self): self.hi_there = tk.Button(self) self.hi_there["text"] = "Hello Worldn(click me)" self.hi_there["command"] = self.say_hi self.hi_there.pack(side="top") self.quit = tk.Button(self, text="QUIT", fg="red", command=root.destroy) self.quit.pack(side="bottom") def say_hi(self): print("hi there, everyone!") root = tk.Tk() app = Application(master=root) app.mainloop() License: CC BY-SA 4.0 (except images), by Jay Coskey 23 Place the "hi_there" button in its parent "frame". Put all the quit button info in this one statement. Create a button. Set the button's text. Loop forever, listening for button clicks. Without this, the program quickly exits. Set the function to be executed on button click. Create and initialie the application window. Place the quit button in its parent "Frame". Create the application window or "frame".
  • 24.
    tkinter layout/geometry managers •The last example had few controls. Richer user experiences are more complex. • tkinter provides three ways of controlling the location of the widgets. • place — This Layout Manager is toooo complicated (for most "use cases") • This requires you to specify the coordinates of each widget being placed. And it doesn't carry over well to the event when a window is resized by the user. It'll drive you nuts. • pack — This Layout Manager is toooo simple (for some "use cases") • This works by declaring for each widget which side(s) of the containing frame it's pushed up against (top, bottom, left, and right). This can work for some layouts, but when you want to do something that involves two sides at once (e.g., having two scroll bars meet in the lower-right corner, but leave a blank space, you'll wish you had chosen grid. • grid — This Layout Manager is juuuust right • You specify a 2-D grid of cells, and declare which widgets lie in which cells. (Think checkers/chess.) Note: Some widgets (e.g., Frame) can contain other widgets, which can contain others. This allows for more complicated layouts (e.g., a Monopoly board). License: CC BY-SA 4.0 (except images), by Jay Coskey 24
  • 25.
    A simple Tkinterlayout License: CC BY-SA 4.0 (except images), by Jay Coskey 25 Chatterbox — □ X Menubar reserved for menus "Dashboard area", for the display the current state of the program. "Control area", for changing the state of the program. Any layout manager can work here, but as the user experience gets more complex, some layout managers become easier to use than others….
  • 26.
    Erik> Wassup? Update Available Tkintercontrols/widgets License: CC BY-SA 4.0 (except images), by Jay Coskey 26 File | Edit | Chat name: Thorvald Asvaldsson Connected as: Send Message: Not much. Just trying to stay warm. Thorvald Asvaldsson Chatterbox — □ X Disconnect ○ Broadcast to all ● Send to individual Send to: Erik Menubar with two menus Label and (text) Entry controls Text control Scrollbar control Lable, Entry, and Button controls Radiobutton, Label, "Dropdown" Button For more info, see https://docs.python.org/3/library/tk.html and http://tkinter.unpythonic.net/wiki/ and https://docs.python.org/3/library/tkinter.ttk.html
  • 27.
    tkinter widgets! • tkinterhas many controls/widgets available to build a GUI with. License: CC BY-SA 4.0 (except images), by Jay Coskey 27 Canvas Checkbutton Frame (text) Entry Button Label Listbox Message Menubutton Menu Text Scrollbar Scale Radiobutton LabelFrame Toplevel Spinbox PanedWindow
  • 28.
    tkinter.ttk — Morewidgets! • If you're going to use tkinter for your Course Project, check out some of these other widgets that are available outside of tkinter. from tkinter import ttk ttk widgets available: Combobox Notebook Progressbar Separator Sizegrip Treeview License: CC BY-SA 4.0 (except images), by Jay Coskey 28 Note: tkinter.ttk replaces an older module called tkinter.tix.
  • 29.
    Other desktop GUIoptions • Again, tkinter is based on the widget toolkit Tk, which was first released in 1991. • Tkinter has long come bundled with Python. But there are other GUI packages available. • Kivy (multi-touch-enabled media rich apps; successor to the PyMT project; MIT license) • Written (from scratch?) by the Kivy foundation; first released in 2011 • Libavg • Based on OpenGL, which was first released in 1992 • PyGi • Based on the GNOME platform, first released in 1999 • PyQt (GPL license) and PySide (LGPL license) • Based on the Qt toolkit, first released in 1995 • wxPython and gui2Py (which is based on wxPython) • Based on wxWidgets, which was first released in 1992 License: CC BY-SA 4.0 (except images), by Jay Coskey 29
  • 30.
    Data Visualization (in2D) with matplotlib and Jupyter 30
  • 31.
    "ReachOne" step countvisualization # See Question 2(b) on HW #4. import matplotlib.pyplot as plt def reachone_next(n: int) -> int: result = n / 2 if n % 2 == 0 else 3 * n + 1 return result def reachone_count(n: int) -> int: count = 0 while n > 1: count += 1 n = reachone_next(n) return count xs = range(1,10001) ys = [reachone_count(x) for x in xs] plt.scatter(xs, ys) plt.show() License: CC BY-SA 4.0 (except images), by Jay Coskey 31 Look — a pattern! One that would not have become apparent, except through such a visualization.
  • 32.
    Palindrome step countvisualization (1) def is_palindrome(n): return str(n) == str(n)[::-1] def reachpalindrome_next(n): return n + int(str(n)[::-1]) def reachpalindrome_step_count(n): count = 0 while not is_palindrome(n): count += 1 n = reachpalindrome_next(n) return count License: CC BY-SA 4.0 (except images), by Jay Coskey 32 Let's try something similar, but • Have the "step" be reversing the digits of a number and adding the reversed number to the original • Repeat until the result is a palindrom, and count the number of steps until that happens. If we use the number 176 as an example, it takes 5 steps to reach a palindrome. 0: 176 1: 176 + 671 = 847 2: 847 + 748 = 1595 3: 1595 + 5951 = 7546 4: 7546 + 6457 = 14003 5: 14003 + 30041 = 44044
  • 33.
    Palindrome step countvisualization (2) import matplotlib.pyplot as plt <... functions as on previous slide ...> pxs = range(1,101) pys = [reachpalindrome_step_count(px) for px in pxs] plt.scatter(pxs, pys) plt.title('ReachPalindrome steps') plt.xlim(-1,101) plt.ylim(-1,25) plt.xlabel('Value') plt.ylabel('Step count') for px in pxs: if pys[px - 1] > 10: py = pys[px - 1] plt.annotate('({0},{1})'.format(px,py), xy=(px,py), xytext=(px-50,py-5-(px-89)), arrowprops=dict(facecolor='black',shrink=0.05)) plt.show() License: CC BY-SA 4.0 (except images), by Jay Coskey 33 The matplotlib package has support for a broad range of means of visualizations. • We can add titles, labels, annotations, etc. • It looks like there are patterns in this "scatterplot" that could lead to other insights….
  • 34.
    Q: Why visualize?A: Anscomb's Quartet • Anscombe's Quartet doesn't have any violins. • It's four sets of 11 points each, created in 1973 by English statistician Francis Anscombe (1918-2001). • Each set has means (x & y coords), variances (x & y), x-y correlations, and best-fit line as each other set. • So if you only look at aggregated statistics, each set looks exactly the same as all the others. • But if you look at the scatter plots of these sets, then they all look quite distinct. • Moral of the story: Visualize your data to better understand it. There might be more to the story. License: CC BY-SA 4.0 (except images), by Jay Coskey 34 You won't come across one of the data sets in Anscombe's Quartet, but a common occurrence is that your dataset looks like it's made up of two or more datasets superimposed. It might make sense to break them apart and study each one separately.
  • 35.
    What is theMandelbrot set? • There's a famous 2-D set in mathematics called the Mandelbrot set (Benoît Mandelbrot, 1924-2010). It's defined similarly—in terms of the number of iterations of a function. License: CC BY-SA 4.0 (except images), by Jay Coskey 35 The idea is simple. Take a particular simple function defined for all points on the (complex) plane. Call it f. • For some points p near the origin, all iterations of f (i.e., f(p), f(f(p)), f(f(f(p))), etc. remain near the origin. • For some other points, iterations of f quickly zoom outward, getting further & further from the origin. • For points inbetween, the pattern is very complex. def mandelbrot_iter_count(x, y, iterations_max): z = 0 c = x + 1j*y # Note: 1j = math.sqrt(-1) iterations_until_divergence = iter_max for k in range(1, iter_max): z = z*z + c if abs(z) > 2: # Divergence iterations_until_divergence = k break return iterations_until_divergence To create the Mandelbrot set, color by numbers: • For the points on the plane that always stay near the origin—give them one color. • For points that quickly zoom away, give them another color. • For points inbetween, given them a color that transitions from one to the other.
  • 36.
    Mandelbrot set visualization •I wonder if Mandelbrot liked almond bread. Anyhow, where were we? License: CC BY-SA 4.0 (except images), by Jay Coskey 36 import matplotlib.pyplot as plt import numpy as np def mandelbrot_iter_counts(xmin, xmax, ymin, ymax, nx=500, ny=500, iter_max=500): dx = (xmax-xmin) / (nx-1) dy = (ymax-ymin) / (ny-1) xs = [xmin + i*dx for i in range(nx)] ys = [ymin + i*dy for i in range(ny)] return [[mandelbrot_iter_count(x, y, iter_max) for x in xs] for y in ys] if __name__ == '__main__': plt.figure() bounds_all = [-1.6, 0.6, -1.1, 1.1] # The entire set bounds_a = [-1.0, -0.5, 0.0, 0.3] # Zoom in bounds_b = [-0.78, -0.73, 0.02, 0.08] # More zoom bounds_c = [-0.752, -0.749, 0.031, 0.0335] # Enhance! (xmin, xmax, ymin, ymax) = bounds_all (nx, ny, iter_max) = (100, 100, 100) plt.imshow(np.array(mandelbrot_iter_counts(xmin,xmax,ymin,ymax, nx,ny,iter_max)), extent=(xmin,xmax,ymin,ymax), origin='lower') plt.show() Note: numpy is used for many high-performance computations
  • 37.
    More data visualizationwith matplotlib • We've barely scratched the surface of matplotlib. • Check out the gallery of matplotlib visualizations at http://matplotlib.org/gallery.html • You can click on any of these visualizations to get the underlying source code. • There are other visualization libraries in Python, including Bokeh (http://bokeh.pydata.org/), which focuses on interactive display. Of course, Bokeh has its own gallery. License: CC BY-SA 4.0 (except images), by Jay Coskey 37
  • 38.
    Jupyter (was IPythonnotebook) (1) • Jupyter is a way of using Python with (distributed) interactive notebooks. • See https://ipython.org/ipython-doc/3/interactive/ for the details. License: CC BY-SA 4.0 (except images), by Jay Coskey 38 • Your script becomes a notebook made of a kernel and console. • A notebook has cells that are chunks of code that can be edited, run, or moved around as needed. • This is a very handy environment, especially for data analysis, where there is often a linear flow of execution involving: • Creating a data model (e.g., weather) • Refining & evolving the model • Running & evaluating the model • Outputting summary information
  • 39.
    Jupyter (was IPythonnotebook) (2) • To run Jupyter on your laptop, run the command ipython notebook • There are many public Jupyter notebooks over at • http://nbviewer.jupyter.org/ License: CC BY-SA 4.0 (except images), by Jay Coskey 39 And there's even more available at github.com. IPython notebooks (.ipynb) files checked into github.com can be viewed as IPython notebooks. Just search on Google for filetype:ipynb site:github.com Example: You can make Deep Dream images using https://github.com/google/deepdream/blob /master/dream.ipynb nbviewer uses nbconvert. Notebooks can be converted to HTML, PDF, or a regular Python file.
  • 40.
  • 41.
    A few morePython language features • Class inheritance and multiple inheritance: • https://docs.python.org/3/tutorial/classes.html#inheritance • "Context managers" (i.e., scoped resources) using "with" statements • https://www.python.org/dev/peps/pep-0343/ • Decorators • https://www.python.org/dev/peps/pep-0318/ • https://python-3-patterns-idioms-test.readthedocs.io/en/latest/PythonDecorators.html • https://dbader.org/blog/python-decorators • Exceptions (a common means of error handling) • https://docs.python.org/3/library/exceptions.html • Iterables, iterators, and generators • http://www.python-course.eu/python3_generators.php • Parameter packing and unpacking (*args and **kwargs) • http://thepythonguru.com/python-args-and-kwargs/ • Aynchronous features (: • https://docs.python.org/3/library/asyncio.html • https://www.youtube.com/watch?v=M-UcUs7IMIM License: CC BY-SA 4.0 (except images), by Jay Coskey 41
  • 42.
    Additional resources • CherryPy(Introduction to web development in Python) • http://cherrypy.org/ • Python the Hard Way: • https://learnpythonthehardway.org/book/ • Python 3 Patterns, Recipes, and Idioms • https://media.readthedocs.org/pdf/python-3-patterns-idioms-test/latest/python-3- patterns-idioms-test.pdf • Python's numerical and scientific libraries • numpy, scipy, pandas (data structures & analysis), astropy (astronomy), sympy (symbolic mathematics), scikit-learn (AI-type library, using "machine learning") • Machine learning (think "artificial intelligence") using Python • http://scikit-learn.org/stable/ • Teach Yourself Programming in Ten Years • http://norvig.com/21-days.html License: CC BY-SA 4.0 (except images), by Jay Coskey 42

Editor's Notes

  • #19 The "Pointy things" image reminds me of this Alessi clock, called "Blow Up": http://www.alessi.com/en/products/detail/fc16-blow-up-wall-clock
  • #25 Cf. Goldilocks and the Three Bears.
  • #26 Asvald "from Vest Agder" (b. 780) Oxen-Thorir Asvaldsson (b. 810) (brother of Naddoddur, who discovered Iceland when he was sailing from Norway to the Faroe Islands) -> Ulf Oxen-Thorisson (c. 850, Norway) -> Asvald(ur) Ulfsson (c. 880) -> Thorvald Asvaldsson (c. 930, Norway) - Exiled from Norway c. 960 for manslaughter. - Went to Iceland w/ son Erik, and died there before 980. -> Erik Thorvaldsson (Erik the Red) (c. 940/950 – c. 1003) - prob. born in Icelandic - Exiled for 3 years for killing Eyiolf the Foul - "Discovered" & colonized Greenland o Greenland was actually sighted about a century earlier, by Norseman Gunnbjorn Ulfsson when he was blown off course while headed from Norway to Iceland. It was settled shortly thereafter by Norseman Snaebjorn Galti c. 900. -> Leif Ericson (c. 970 – c. 1020) (visited North America)
  • #27 The "Dropdown" control is actually called an OptionMenu. Asvald "from Vest Agder" (b. 780) Oxen-Thorir Asvaldsson (b. 810) (brother of Naddoddur, who discovered Iceland when he was sailing from Norway to the Faroe Islands) -> Ulf Oxen-Thorisson (c. 850, Norway) -> Asvald(ur) Ulfsson (c. 880) -> Thorvald Asvaldsson (c. 930, Norway) - Exiled from Norway c. 960 for manslaughter. - Went to Iceland w/ son Erik, and died there before 980. -> Erik Thorvaldsson (Erik the Red) (c. 940/950 – c. 1003) - prob. born in Icelandic - Exiled for 3 years for killing Eyiolf the Foul - "Discovered" & colonized Greenland o Greenland was actually sighted about a century earlier, by Norseman Gunnbjorn Ulfsson when he was blown off course while headed from Norway to Iceland. It was settled shortly thereafter by Norseman Snaebjorn Galti c. 900. -> Leif Ericson (c. 970 – c. 1020) (visited North America)
  • #30 A comparison of PyQt and wxPython, including source code examples: https://opensource.com/article/17/4/pyqt-versus-wxpython As of April, 2017, wxPython still does not support Python 3.
  • #39 There are some excellent Jupyter notebooks available at http://nbviewer.jupyter.org/github/donnemartin/interactive-coding-challenges/tree/master/
  • #40 There are some excellent Jupyter notebooks available at http://nbviewer.jupyter.org/github/donnemartin/interactive-coding-challenges/tree/master/
  • #42 Different ways of achieving async in Python: https://quentin.pradet.me/blog/what-color-is-your-python-async-library.html
  • #43 Splitting images into smaller images: https://www.reddit.com/r/learnpython/comments/2jlv1e/python_script_to_take_an_image_and_cut_it_into_4/ A Neural Network in 11 Lines of Python (Part 1): http://iamtrask.github.io/2015/07/12/basic-python-network/ Playing music using Python: https://www.reddit.com/r/Python/comments/63ioos/python_music_player/ Single-image cheatsheet on Python for big data: https://i.redd.it/jcrdi4piruqy.png