You've started the Codecademy and Coursera courses; you've thumbed through Zed Shaw's "Learn Python the Hard Way"; and now you're itching to see what Python can help you do. This is the workshop for you!
Here's the breakdown: we're going to be taking you on a whirlwind tour of Python's capabilities. By the end of the workshop, you should be able to easily follow any of the widely available Python courses on the internet, and have a grasp on some of the more complex aspects of the language.
Please don't forget to bring your personal laptop!
Audience: This course is aimed at those who already have some basic programming experience, either in Python or in another high level programming language (such as C/C++, Fortran, Java, Ruby, Perl, or Visual Basic). If you're an absolute beginner -- new to Python, and new to programming in general -- make sure to check out the "Python 101" workshop!
4. for Loops
Beatles = [“John”, “Paul”, “George”, “Ringo”]
for Beatle in Beatles:
print Beatle
John
Paul
George
Ringo
5. while Loops
temperature = 115
while temperature > 112:
print(temperature)
temperature = temperature – 1
print “The coffee is cool enough to drink.”
6. Conditionals (if – elif – else)
>>> x = int(raw_input(“Please enter the answer to life, the
universe, and everything: “))
Please enter the answer to life, the universe, and everything:
42
>>> if x < 0:
x = 0
print ‘Negative changed to zero.’
elif x == 0:
print ‘Zero’
elif x == 1:
print ‘Single’
else:
print ‘More’
More
7. Input
>>> def beverage(drink):
print “Have you had a cup of “ + str(drink) + “ today?”
>>> def beverage():
print “Type your favorite drink:”
drink = raw_input()
print “Have you had a cup of “ + str(drink) + “today?”
>>> beverage()
10. CodeSkulptor
Developed by Scott Rixner of Rice
University to use for COMP 200.
Based on CodeMirror and Skulpt.
www.codeskulptor.org
If you want to learn more about
using Python with CodeSkulptor
after this class, check out the
Coursera course “An Introduction
to Interactive Programming in
Python”! (9/15 – 11/16)
https://www.coursera.org/course/
interactivepython
14. Objects
In the real world, objects have:
Things that you can do to them
(actions)
Words that describe them
(properties)
In Python:
“Things that you can do” to an
object are called methods.
“Words that describe” an object
are called attributes.
15. Objects
If this truly spectacular car was an object named
myCar, it might have these attributes:
myCar.color
myCar.maxspeed
myCar.electricityUsage
myCar.weight
myCar.price
You can display them:
print myCar.price
You can assign values to them:
myCar.color = ‘red’
You can assign them to attributes in other objects:
anotherCar.color = myCar.color
16. Objects
The car might have these methods:
myCar.drive()
myCar.wash()
myCar.charge()
myCar.tuneUp()
Methods are the things you can do with an object.
Methods are chunks of code – functions – that are
included inside the object.
17. Objects
In Python, a class is like a description – or
blueprint – of an object.
class Tesla:
color = ‘red’
size = ‘full-size’
type = ‘luxury’
manufacturer = ‘Tesla_Motors’
direction = ‘’
def drive(self_in_circles):
if self.direction == ‘north’:
self.direction == ‘west’
elif self.direction == ‘west’:
self.direction == ‘south’
elif self.direction == ‘south’:
self.direction == ‘east’
else:
self.direction == ‘north’
19. Modules
A module is a block of code that can be combined with other blocks to build a
program.
You can use different combinations of modules to do different jobs, just like
you can combine the same LEGO blocks in many different ways.
Python has a lot of functions that come built-in
GitHub also has extensive user-contributed Python libraries
There’s no reason to invent the wheel! If someone has created a module that
accomplishes a specific task you needed to accomplish, there’s no reason for
you to put forth the effort.
20. Modules
Generate a random number
between 1 – 100:
Raise 2 to the power of 3
Get the current time
Find the first match, if any, of the
regular expression pattern in the
given text string
>>> import random
>>> print random.randint(1, 100)
61
>>> import math
>>> print math.pow(2, 3)
8.0
>>> import time
>>> print time.time()
1412237964.76
>>> import re
>>> print re.search(r’ZZZ’, ‘PyTexas 2014!’)
None
23. List Methods
A list is a mutable (changeable) sequence of values of any type.
A list with zero elements is called an empty list.
List elements are indexed by sequential integers, starting with zero.
print [ ] # the empty list
print [1, 2, 3, 8, 9] # a list of numbers
print [(1,2), ‘hello’, 3, [‘a’, ‘b’, ‘c’]] # a list of a tuple, string, integer, list
24. range()
Arithmetic progressions list, often used in for loops
>>> print range(5)
>>> print range(1, 10)
>>> print range(-10, 100, 20)
>>> print range(100, -10, -20)
>>> for i in range(5):
print i
[0, 1, 2, 3, 4]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[-10, 10, 30, 50, 70, 90]
[100, 80, 60, 40, 20, 0]
0
1
2
3
4
25. list.append() and list.extend()
Adds item to the end of the list; and adds multiple items to the end of a list
a_list = [1, 2, 3]
a_list.append(4)
a_list.append([5, 6, 7])
print a_list
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list1.append([4, 5, 6])
list2.extend([4, 5, 6])
print list1
print list2
a_list = [1, 2, 3]
a_list.extend([4, 5, 6])
a_list.extend((7, 8))
a_list.extend('abc')
a_list.extend({'d': 'e', 'f': 'g'})
[1, 2, 3, 4, [5, 6, 7]]
[1, 2, 3, [4, 5, 6]]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7, 8, 'a', 'b', 'c', 'd', 'f']
26. list.insert()
Inserts items into a list at a given position.
a_list = ['a', 'b', 'c']
a_list.insert(1, 'x')
print a_list
a_list.insert(0, 'y')
print a_list
a_list.insert(5, 'z')
print a_list
['a', 'x', 'b', 'c']
['y', 'a', 'x', 'b', 'c']
['y', 'a', 'x', 'b', 'c', 'z']
27. list.remove() and list.pop()
Removes an item from a list by value; removes an item from a list by position.
a_list = ['a', 'b', 'c', 'b']
a_list.remove('b')
print a_list
a_list = ['a', 'b', 'c']
print a_list.pop(1)
print a_list
['a', 'c', 'b']
b
['a', 'c']
If no position is specified for .pop(), it
defaults to the last item.
28. list.reverse(), list.sort(), and list()
Reverses items in a list; sorts items in a list; converts an iterable or iterator into a list.
a_list = [1, 2, 3]
a_list.reverse()
print a_list
a_list = [2, 1, 3, 2]
a_list.sort()
print a_list
print list()
print list(‘abc’)
print list([1,2,3,4,5])
print list((1,2,3,4,5))
print list({1:2, 3:4})
print list(enumerate([‘a’,’b’,’c’,’d’]))
[3, 2, 1]
[1, 2, 2, 3]
[]
[‘a’, ‘b’, ‘c’]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4]
[1, 3]
[(0, ‘a’), (1, ‘b’), (2, ‘c’), (3, ‘d’)]
30. String Methods
A string is an immutable (unchangeable) sequence of characters.
The string with zero characters is called an empty string.
String elements are indexed by sequential integers, starting with zero.
print “”
print ‘Hello, world!’
print “Good-bye, cruel world.”
print “This is
a multi-line
string.”””
' single quote character
" double quote character
backslash character
b backspace character
f formfeed character
n new line character (starts a new line)
r carriage return character
t horizontal tab character (moves to next tab position,
which is every eight characters)
v vertical tab character
32. str.join(), str.split(), and str.partition()
Concatenates iterable sequences into strings; splits string at delimiters. .
print ‘,’.join(‘abcd’)
print ‘ ‘.join([‘a’,’bc’,’d’])
print ‘zz’.join((‘a’,’bc’,’d’))
print ‘ ‘.join({‘a’:’x’,’b’:’y’})
print ‘ ‘.join(set([‘a’,’b’]))
print ‘a b c’.partition(‘ ‘)
print ‘a b c’.rpartition(‘ ‘)
print ‘a bc d’.split()
print ‘a bc d’.split(None)
print ‘a bc d’.split(‘ ‘)
print ‘a bc d’.split(‘ ‘)
print ‘a bc d’.split(‘b’)
print ‘ababbaaaa’.split(‘a’,2)
a,b,c,d
a bc d
azzbczzd
a b
a b
('a', ' ', 'b c')
(‘a b', ' ', 'c')
[‘a’, ‘bc’, ‘d’]
[‘a’, ‘bc’, ‘d’]
[‘a’, ‘’,’’,‘bc’, ‘d’]
[‘a’, ‘ bc d’]
[‘a ’, ‘c d’]
[‘’, ‘b’, ‘bbaaaaa’]
33. str.capitalize(), str.upper (), and str.lower()
Capitalizes a string; changes the case of a string.. .
print ‘peAr’.capitalize()
print ‘abc123DEF’.upper()
print ‘abc123DEF’.lower()
Pear
ABC123DEF
abc123def
37. Dictionaries
A dictionary is a mutable (changeable) mapping of keys to values.
A dictionary with no keys is called an empty dictionary.
Also known as associative memories, associative arrays, or hashmaps.
Dictionaries are unordered because they are indexed by keys, which can be of any
immutable (unchangeable) type.
When printed, iterated upon, or converted into a sequence, a dictionary’s elements will
appear in an arbitrary, implementation-dependent order.
print {}
print {1: 'a', 2: 'b', 9: 'c'}
print {1: 'a', (5, 'item'): [100], 'key': {True: 'hello', -9: 0}}
38. dict(), dict[], dict.get(), dict[key] = value
Converts iterable of pairs into a dictionary; gets and sets value in a dictionary by key.
print dict()
print dict([(1,’a’),(1,’b’),(3,’c’)])
print dict(((1,’a’),(2,’b’),(3,’c’)))
print dict(enumerate([‘a’,’b’,’c’,’d’]))
print {1:’a’, 2:’b’, 3:’c’}[2]
print {1:’a’, 2:’b’, 3:’c’}.get(2)
print {1:’a’, 2:’b’, 3:’c’}.get(7)
print {1:’a’, 2:’b’, 3:’c’}.get(7, ‘not here’)
d = {1: 'a', 2: 'b', 3: 'c'}
d[2] = 'd'
print d
d[5] = 'e'
print d
{}
{1:’a’, 2: ‘b’, 3: ‘c’}
{1:’a’, 2: ‘b’, 3: ‘c’}
{0:’a’, 1: ‘b’, 2: ‘c’, 3:’d’}
b
b
None
not here
{1: 'a', 2: 'd', 3: 'c'}
{1: 'a', 2: 'd', 3: 'c', 5: 'e'}
39. dict.has_key() and dict.pop()
Checks to see if a key is in a dictionary; removes key from dictionary and returns its value.
print {1: 'a', 2: 'b', 3:
'c'}.has_key(2)
print {1: 'a', 2: 'b', 3:
'c'}.has_key(4)
d = {1: 'a', 2: 'b', 3: 'c'}
print d.pop(1)
print d
d = {1: 'a', 2: 'b', 3: 'c'}
print d.pop(1, 'xyz')
print d
d = {1: 'a', 2: 'b', 3: 'c'}
print d.pop(4)
print d
d = {1: 'a', 2: 'b', 3: 'c'}
print d.pop(4, 'xyz')
print d
True
False
a
{2: 'b', 3: 'c'}
a
{2: 'b', 3: 'c'}
Line 2: KeyError: 4
xyz
{1: 'a', 2: 'b', 3: 'c'}
40. dict.items (), dict.keys(), dict.values()
Gets a list of all key/value pairs in a dictionary; gets a list of all keys; gets a list of all values.
print {1: 'a', 2: 'b', 3: 'c'}.items()
sample_dict = {1: 'a', 2: 'b', 3: 'c'}
for key, value in sample_dict.items():
print key, 'maps to', value
print {1: 'a', 2: 'b', 3: 'c'}.keys()
print {1: 'a', 2: 'b', 3: 'c'}.values()
sample_dict = {1: 'a', 2: 'b', 3: 'c'}
for value in sample_dict.values():
print value, 'is a value in the
dictionary'
[(1, 'a'), (2, 'b'), (3, 'c')]
1 maps to a
2 maps to b
3 maps to c
[1, 2, 3]
['a', 'b', 'c']
a is a value in the dictionary
b is a value in the dictionary
c is a value in the dictionary
49. set()
A set is an unordered collection without duplicates.
When printed, iterated upon, or converted into a sequence, its elements will
appear in an arbitrary, implementation-dependent order.
print set()
print set(‘abc’)
print set([1,2,3,4,5,3,5])
print set((1,2,3,4,5))
print set(set([1,2,3,4]))
print set({1:2, 3:4})
print set(enumerate([‘a’,’b’,’c’,’d’]))
set()
set([‘a’, ‘b’, ‘c’])
set([1,2,3,4,5])
set([1,2,3,4,5])
set([1,2,3,4])
set([1, 3])
set([(0, ‘a’),(1, ’b’),(2, ’c’),(3, ’d’)])
54. Frame
A frame is a window, which is a container for the controls, status information, and canvas.
A program can create only one frame.
# Create frame
# Syntax: simplegui.create_frame(title, canvas_width, canvas_height)
# Syntax: simplegui.create_frame(title, canvas_width, canvas_height, control_width)
frame = simplegui.create_frame('Testing', 100, 100)
frame = simplegui.create_frame('Testing', 200, 200, 300)
# Set the frame’s background color
# Syntax: frame.set_canvas_background(color)
frame = simplegui.create_frame('Testing', 100, 100)
frame.set_canvas_background('Red')
frame.start()
# Start frame’s interactivity
frame = simplegui.create_frame('Testing', 100, 100)
frame.start()
# Get Canvas Text’s Width
# Syntax: frame.get_canvas_textwidth(text, size)
# Syntax: frame.get_canvas_textwidth(text, size, face)
frame = simplegui.create_frame('Testing', 100, 100) print frame.get_canvas_textwidth('hello', 12)
frame = simplegui.create_frame('Testing', 100, 100) print frame.get_canvas_textwidth('hello', 12, 'sans-serif')
55. Control Objects
Control objects are placed in the control panel, which is the left-hand part of the frame. They are placed top-down
in the order of creation.
# Add a text label to the frame control panel
# Syntax: frame.add_label(text)
frame = simplegui.create_frame('Testing', 100, 100)
label = frame.add_label('My label')
# Add a button to the frame control panel
# Syntax: frame.add_button(text, button_handler)
# Syntax: frame.add_button(text, button_handler, width)
frame = simplegui.create_frame('Testing', 100, 100)
button1 = frame.add_button('Label 1', button_handler)
button2 = frame.add_button('Label 2', button_handler, 50)
# Add text input to the frame control panel
# Syntax: frame.add_input(text, input_handler, width)
frame = simplegui.create_frame('Testing', 100, 100)
inp = frame.add_input('My label', input_handler, 50)
# Get the text of control object
# Syntax: control.get_text()
frame = simplegui.create_frame('Testing', 100, 100)
print frame.get_canvas_textwidth('hello', 12, 'sans-serif')
56. Control Objects, ctd.
Control objects are placed in the control panel, which is the left-hand part of the frame. They are placed top-down
in the order of creation.
# Set the text of a control object
# Syntax: control.set_text(text)
frame = simplegui.create_frame('Testing', 100, 100)
label = frame.add_label('Label')
label.set_text('New label')
# Set the keyboard input handler
# Syntax: frame.set_keydown_handler(key_handler)
# Syntax: frame.set_keyup_handler(key_handler)
def key_handler(key):
…
frame = simplegui.create_frame('Testing', 100, 100)
frame.set_keydown_handler(key_handler)
frame.start()
# Set the mouse input handler
# Syntax: frame.set_mouseclick_handler(mouse_handler)
# Syntax: frame.set_mousedrag_handler(mouse_handler)
def mouse_handler(position):
…
frame = simplegui.create_frame('Testing', 100, 100)
frame.set_mouseclick_handler(mouse_handler)
frame.start()
57. Canvas
The canvas is where you can draw text and shapes.
# Set the draw handler on Canvas
# Syntax: frame.set_draw_handler(draw_handler)
def draw_handler(canvas):
…
frame = simplegui.create_frame('Testing', 100, 100)
frame.set_draw_handler(draw_handler)
frame.start()
# Draw text on Canvas
# Syntax: canvas.draw_text(text, point, font_size, font_color)
# Syntax: canvas.draw_text(text, point, font_size, font_color, font_face)
def draw_handler(canvas):
canvas.draw_text('A', (20, 20), 12, 'Red')
canvas.draw_text('B', [30, 50], 20, 'Blue')
canvas.draw_text('C', (80, 50), 12, 'Gray', 'serif')
frame = simplegui.create_frame('Testing', 100, 100)
frame.set_draw_handler(draw_handler)
frame.start()
# Draw line segment on Canvas
# Syntax: canvas.draw_line(point1, point2, line_width, line_color)
def draw_handler(canvas):
canvas.draw_line((10, 20), (30, 40), 12, 'Red')
canvas.draw_line([10, 20], [80, 70], 20, 'Blue')
frame = simplegui.create_frame('Testing', 100, 100)
frame.set_draw_handler(draw_handler)
frame.start()
# Draw connected line segments on Canvas
# Syntax: canvas.draw_polyline(point_list, line_width, line_color)
def draw_handler(canvas):
canvas.draw_polyline([(10, 20), (30, 20), (90, 70)], 12, 'Red')
canvas.draw_polyline([[40, 20], [80, 40], [30, 90]], 20, 'Blue')
frame = simplegui.create_frame('Testing', 100, 100)
frame.set_draw_handler(draw_handler)
frame.start()
59. Timers
A timer calls an event handler repeatedly at a specified interval.
# Create a timer
# Syntax: simplegui.create_timer(interval, timer_handler)
def timer_handler():
…
timer = simplegui.create_timer(500, timer_handler)
timer.start()
# Start timer
# Syntax: timer.start()
# Stop timer
# Syntax: timer.stop()
# Check if timer is running
# Syntax: timer.is_running()
def timer_handler():
pass
timer = simplegui.create_timer(100, timer_handler)
print timer.is_running()
timer.start()
print timer.is_running()
timer.stop()
print timer.is_running()
60. Images
An image must be loaded before it can be drawn.
# Load image
# Syntax: simplegui.load_image(URL)
def draw_handler(canvas):
canvas.draw_image(image, (1521 / 2, 1818 / 2), (1521, 1818), (50, 50), (100, 100))
image = simplegui.load_image('http://commondatastorage.googleapis.com/codeskulptor-assets/gutenberg.jpg')
frame = simplegui.create_frame('Testing', 100, 100)
frame.set_draw_handler(draw_handler)
frame.start()
# Get image’s width
# Syntax: image.get_width()
# Get image’s height
# Syntax: image.get_height()
61. Sounds
A sound must be loaded before it can be played.
# Load sound
# Syntax: simplegui.load_sound(URL)
sound = simplegui.load_sound('http://commondatastorage.googleapis.com/codeskulptor-assets/Epoq-Lepidoptera.ogg')
sound.set_volume(0.7)
# Play sound
# Syntax: sound.play()
sound = simplegui.load_sound('http://commondatastorage.googleapis.com/codeskulptor-assets/Epoq-Lepidoptera.ogg')
sound.play()
# Pause sound
# Syntax: sound.pause()
sound = simplegui.load_sound('http://commondatastorage.googleapis.com/codeskulptor-assets/Epoq-Lepidoptera.ogg')
sound.play()
sound.pause()
# Rewind sound
# Syntax: sound.rewind()
sound = simplegui.load_sound('http://commondatastorage.googleapis.com/codeskulptor-assets/Epoq-Lepidoptera.ogg')
sound.play()
sound.rewind()
sound.play()
# Set sound’s volume
# Syntax: sound.set_volume()
sound = simplegui.load_sound('http://commondatastorage.googleapis.com/codeskulptor-assets/Epoq-Lepidoptera.ogg')
sound.set_volume(0.7)
62. Maps
SimpleMap module provides an interface for drawing and annotating maps. The underlying maps are provided by Google
Maps. Points on the map are referred to by (lat,long). The module uses three kinds of objects: maps, markers, and lines.
# Create map
# Syntax: simplemap.create_map(title, coordinates, map_width, map_height)
# Syntax: simplemap.create_map(title, coordinates, map_width, map_height, control_width)
simplemap.create_map('Rice University', (29.716467, -95.404213), 500, 500)
# Add marker to a map
# Syntax: a_map.add_marker(description, id, icon_url, coordinates, handler)
# Draw line on a map
# Syntax: a_map.draw_line(start_marker, stop_marker)
# Get a set of all markers on a map
# Syntax: a_map.get_markers()
# Get a set of all lines from the map
# Syntax: a_map.get_lines()
# Clear all markers from the map
# Syntax: a_map.clear_markers()
63. Maps, ctd.
SimpleMap module provides an interface for drawing and annotating maps. The underlying maps are provided by Google
Maps. Points on the map are referred to by (lat,long). The module uses three kinds of objects: maps, markers, and lines.
# Clear all lines from the map
# Syntax: a_map.clear_lines()
# Clear everything from the map
# Syntax: a_map.clear()
# Add button control to the map
# Syntax: a_map.add_button(text, handler)
# Syntax: a_map.add_button(text, handler, width)
# Add line break to map control panel
# Syntax: a_map.add_break()
64. Markers
A marker object corresponds to a drawn marker icon image on the map. Its location is determine by (lat,long).
# Get description of marker
# Syntax: a_marker.get_description()
# Get ID of marker
# Syntax: a_marker.get_id()
# Get coordinates of marker
# Syntax: a_marker.get_coordinates()
# Get icon URL of marker
# Syntax: a_marker.get_icon()
# Set icon of marker
# Syntax: a_marker.set_icon()
# Remove marker from map
# Syntax: a_marker.remove()
65. Lines
A line object corresponds to a drawn path between two markers on the map. The path follows the available streets on the
map. The path color defaults to black.
# Get start marker of line
# Syntax: a_line.get_start()
# Get stop marker of line
# Syntax: a_line.get_stop()
# Set color of line
# Syntax: a_line.set_color()
# Remove line from the map
# Syntax: a_line.remove()