SlideShare a Scribd company logo
Python 101++ 
Let’s Get Down to Business! 
PyTexas 2014
Just as a refresher…
Data Types 
 Integers 
 Floating-point numbers 
 Booleans 
 Strings 
 Tuples 
 Lists 
 Dictionaries 
42 
3.1416 
True 
“Gig ‘em!” 
(27.174885 , 78.039794) 
[“Ian”, “Kevin”, Curtis”] 
{1: ‘a’, 2: ‘b’, 9: ‘c’}
for Loops 
Beatles = [“John”, “Paul”, “George”, “Ringo”] 
for Beatle in Beatles: 
print Beatle 
John 
Paul 
George 
Ringo
while Loops 
temperature = 115 
while temperature > 112: 
print(temperature) 
temperature = temperature – 1 
print “The coffee is cool enough to drink.”
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
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()
Booleans 
and, or, not, any, all
CodeSkulptor!
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
Interacting with CodeSkulptor 
 Run 
 Save 
 Fresh URL 
 Open Local 
 Reset
Additional Resources 
 Docs (documentation) 
 Demos 
 Viz Mode
Objects
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.
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
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.
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’
Modules
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.
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
Types and Operations
List Methods
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
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
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']
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']
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.
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’)]
String Methods
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
str() 
Converts values into a string. 
print str() 
print str(4859202) 
print str(True) 
print str(‘abc’) 
print str(None) 
print str([1, 2, 3, 4, 5]) 
print str((1, 2, 3, 4, 5)) 
print str({1: ‘a’, 2: ‘b’, 3: ‘c’}) 
print str(set([1, 2, 3, 4, 5])) 
print str(str) 
# the empty string 
4859202 
True 
abc 
None 
(1, 2, 3, 4, 5) 
[1, 2, 3, 4, 5] 
{1: ‘a’, 2: ‘b’, 3: ‘c’} 
set([1, 2, 3, 4, 5]) 
<class ‘str’>
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’]
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
str.find(), str.index(), and str.replace() 
Finds a substring; replaces a substring. 
print ‘abcdabcd’.find(‘bc’) 
print ‘abcdabcd’.find(‘bc’, 3) 
print ‘abcdabcd’.rfind(‘bc’) 
print ‘abcdabcd’.rfind(‘bc’, 3) 
print ‘abcdabcd’.find(‘f’) 
print ‘abcdabcd’.rfind(‘f’) 
print ‘abcdabcd’.find(‘bc’, 6) 
print ‘abcdabcd’.rfind(‘bc’, 6) 
print ‘abcdabcd’.find(‘bc’, 3, 6) 
print ‘abcdabcd’.replace(‘bc’, ‘f’) 
print ‘abcdabcd’.replace(‘bc’, ‘f’, 1) 
print ‘abcdabcd’.replace(‘g’, ‘f’) 
print ‘aaaaa’.replace(‘aa’, ‘f’) 
1 
5 
5 
5 
-1 
-1 
-1 
-1 
-1 
afdafd 
afdabcd 
abcdabcd 
ffa
str.startswith(), str.endswith(), and str.isdigit() 
Checks prefix; checks suffix; checks whether the string contains a digit. 
print ‘silly string’.startswith(‘sil’) 
print ‘silly string’.startswith(‘ing’) 
print ‘silly string’.endswith(‘sil’) 
print ‘silly string’.endswith(‘ing’) 
print ‘’.isdigit() 
print ‘1234’.isdigit() 
print ‘1234abc’.isdigit() 
print ' cde fgh '.strip() 
print ' cde fgh '.strip(None) 
print ‘aaababcdeafghbaba'.strip(‘ab’) 
print ' cde fgh '.lstrip() 
print ‘aaababcdeafghbaba’.strip() 
print ' cde fgh '.rstrip() 
print ‘aaababcdeafghbaba’.strip() 
True 
False 
False 
True 
False 
True 
False 
cde fgh 
cde fgh 
cdeafgh 
cde fgh 
cdeafghbaba 
cde fgh 
aaababcdeafgh
Dictionary Methods
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}}
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'}
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'}
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
Sequences
Sequences: slicing and counting 
list[i:j:k], list.count() 
print ‘abcde’[1:3] 
print (8, 2, 4, 0)[1:-1] 
print [8, 2, 4, 0][1:] 
print 'abcde'[1:4:2] 
print (8, 2, 4, 0)[1::1] 
print [8, 2, 4, 0][::-1] 
print ['a', 'b', 'c', 'b', 'a', 'c'].count('b') 
print ('a', 'b', 'c', 'b', 'a', 'c').count('b') 
print 'abcbac'.count('c') 
print 'abcbac'.count('cb') 
print ['a', 'b', 'c', 'b', 'a', 'c'].count('b', 3) 
print ('a', 'b', 'c', 'b', 'a', 'c').count('b', 3) 
print 'abcbac'.count('b', 3) 
print ['a', 'b', 'c', 'b', 'a', 'c'].count('b', 2, 3) 
print ('a', 'b', 'c', 'b', 'a', 'c').count('b', 2, 3) 
print 'abcbac'.count('b', 2, 3) 
bc 
(2, 4) 
[2, 4, 0] 
bd 
(2, 4, 0) 
[0, 4, 2, 8] 
2 
2 
2 
1 
1 
1 
1 
0 
0 
0
Iterables
in, not in, and len() 
Tests if an item is in an iterable or not; tests the length of the iterable. 
print 8 in [1, 2, 3, 4, 5, 6, 7] 
print 'c' in 'abcde‘ 
print (1,3) in ('a', 3, 4, (1,2), 'hello') 
print 3 in {1: 'a', 2: 'b', 3: 'c'} 
print 3 in {'a': 1, 'b': 2, 'c: 3} 
print 8 in set([1, 2, 3, 4, 5, 6, 7]) 
print 8 not in [1, 2, 3, 4, 5, 6, 7] 
print 'c' not in 'abcde’ 
print (1,3) not in ('a', 3, 4, (1,2), 'hello') 
print 3 not in {1: 'a', 2: 'b', 3: 'c'} 
print 3 not in {'a': 1, 'b': 2, 'c: 3} 
print 8 not in set([1, 2, 3, 4, 5, 6, 7]) 
print len('') 
print len([2, 35, -2, 12]) 
print len((2, 35, -2, 12)) 
print len({1: 2, 3: 4}) 
print len(set([2, 35, -2, 12])) 
False 
True 
False 
True 
False 
False 
True 
False 
True 
False 
True 
True 
0 
4 
4 
2 
4
sum(), max(), and min() 
Sum of elements in an iterable; maximum and minimum value among multiple inputs or in iterable. 
print sum([10, 20, 30]) 
print sum((10, 20, 30)) 
print sum({1: 10, 2: 20}) 
print sum(set([10, 20, 30)])) 
print sum([10, 20, 30], 2) 
print max(2, 35, -2, 12) 
print max('c', 'x', 'cat', 'father') 
print max([2, 35, -2, 12]) 
print max(['c', 'x', 'cat', 'father']) 
print max((2, 35, -2, 12)) 
print max({1: 2, 3: 4}) 
print max(set([2, 35, -2, 12])) 
print min(2, 35, -2, 12) 
print min('c', 'x', 'cat', 'father') 
print min([2, 35, -2, 12]) 
print min(['c', 'x', 'cat', 'father']) 
print min((2, 35, -2, 12)) 
print min({1: 2, 3: 4}) 
print min(set([2, 35, -2, 12])) 
60 
60 
3 
60 
62 
35 
x 
35 
x 
35 
3 
35 
-2 
c 
-2 
c 
-2 
1 
-2
zip() and map() 
Combines the ith elements of iterables into tuples; applies a function to iterable elements. 
print zip('abcd', '1234', (5, 6, 7, 8)) 
print zip([1, 2, 3, 4], ['a', 'b', 'c']) 
print zip({1: 2, 3: 4}, set([5, 6])) 
print zip([1, 2, 3]) 
print zip() 
list1 = ['a', 'b', 'c', 'd', 'e'] 
list2 = ['z', 'y', 'x', 'w', 'v'] 
for letter1, letter2 in zip(list1, list2): 
print letter1 + letter2 
zipped_list = [(1, 'a'), (2, 'b'), (3, 'c')] 
first_elts, second_elts = zip(*zipped_list) 
print first_elts 
print second_elts 
def square(n): 
return n * n 
print map(square, [3, 7, 1]) 
[('a', '1', 5), ('b', '2', 6), ('c', 
'3', 7), ('d', '4', 8)] 
[(1, 'a'), (2, 'b'), (3, 'c')] 
[(1, 5), (3, 6)] 
[(1,), (2,), (3,)] 
[] 
az 
by 
cx 
dw 
ev 
[1, 2, 3] 
['a', 'b', 'c'] 
[9, 49, 1]
filter() and reduce() 
Filters iterable’s elements into a sequence; combines iterable’s elements by applying a function. 
def is_positive(n): 
return n > 0 
print filter(is_positive, [3, -7, 1]) 
def is_positive(n): 
return n > 0 
print filter(is_positive, (3, -7, 1)) 
def is_aorb(x): 
return x == 'a' or x == 'b' 
print filter(is_aorb, 'acdba') 
def is_positive(n): 
return n > 0 
print filter(is_positive, set([3, -7, 1])) 
print filter(None, [set(), 3, {}, 0, False, '', -1, []) 
def add(x, y): 
return x + y 
print reduce(add, [3, -7, 1]) 
def add(x, y): 
return x + y 
print reduce(add, (3, -7, 1), 12) 
def maximum(x, y): 
if x >= y: return x 
else: return y 
print reduce(maximum, 'acdba', 'a') 
def maximum(x, y): 
if x >= y: return x 
else: return y 
print reduce(maximum, 'acdba', 'z') 
def second(x, y): 
return y 
print reduce(second, [1, 2, 3, 4, 5]) 
[3,1] 
(3,1) 
‘aba’ 
[1,3] 
[3,-1] 
-3 
9 
‘d’ 
‘z’ 
5
Sets
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’)])
set.union(), set.intersection(), set.difference, 
set.symmetric_difference() 
print set([1, 2, 3, 4, 5]).union(set([5, 6, 7])) 
print set([1, 2, 3, 4, 5]).intersection(set([5, 6, 7])) 
print set([1, 2, 3, 4, 5]).difference(set([5, 6, 7])) 
print set([1, 2, 3, 4, 5]).symmetric_difference(set([5, 6, 7])) 
# With mutations 
s = set([1, 2, 3, 4, 5]) 
s.update(set([5, 6, 7])) 
print s 
s = set([1, 2, 3, 4, 5]) 
s.intersection_update(set([5, 6, 7])) 
print s 
s = set([1, 2, 3, 4, 5]) 
s.difference_update(set([5, 6, 7])) 
print s 
s = set([1, 2, 3, 4, 5]) 
s.symmetric_difference_update(set([5, 6, 7])) 
print s 
set([1, 2, 3, 4, 5, 6, 7]) 
set([5]) 
set([1, 2, 3, 4]) 
set([1, 2, 3, 4, 6, 7]) 
set([1, 2, 3, 4, 5, 6, 7]) 
set([5]) 
set([1, 2, 3, 4]) 
set([1, 2, 3, 4, 6, 7])
set.add(), set.remove(), set.discard(), set.pop() 
Adds an element in a set; removes specified or arbitrary item from a set. 
s = set([1, 2, 3, 4, 5]) 
s.add(5) 
print s 
s.add(6) 
print s 
s = set([1, 2, 3, 4, 5]) 
s.remove(5) 
print s 
s.discard(7) 
print s 
s.discard(3) 
print s 
s = set([1, 2, 3, 4, 5]) 
print s.pop() 
print s 
set([1, 2, 3, 4, 5]) 
set([1, 2, 3, 4, 5, 6]) 
set([1, 2, 3, 4]) 
set([1, 2, 3, 4]) 
set([1, 2, 4]) 
1 
set([2, 3, 4, 5])
set.issubset(), set.issuperset(), set.copy() 
Tests for subsets and supersets; copies a set. 
print set([2, 9, 7, 1].issubset(s) 
print set([2, 9, 7, 1].issubset(set([1, 7])) 
print set([2, 9, 7, 1].issubset(set([1, 2, 3, 4])) 
print set([2, 9, 7, 1].issubset(set([1, 2, 3, 4, 5, 6, 7, 8, 9])) 
print set([2, 9, 7, 1].issuperset(s) 
print set([2, 9, 7, 1].issuperset(set([1, 7])) 
print set([2, 9, 7, 1].issuperset(set([1, 2, 3, 4])) 
print set([2, 9, 7, 1].issuperset(set([1, 2, 3, 4, 5, 6, 7, 8, 9])) 
s = set([1, 2, 3, 4, 5]) 
t = s.copy() 
print s == t 
print s is t 
True 
False 
False 
True 
True 
True 
False 
False 
True 
False
Graphics Modules
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')
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')
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()
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()
Canvas, ctd. 
The canvas is where you can draw text and shapes. 
# Draw polygon on Canvas 
# Syntax: canvas.draw_polygon(point_list, line_width, line_color) 
# Syntax: canvas.draw_polygon(point_list, line_width, line_color, fill_color = color) 
def draw_handler(canvas): 
canvas.draw_polygon([(10, 20), (20, 30), (30, 10)], 12, 'Green') 
canvas.draw_polygon([[30, 20], [40, 40], [50, 20], [10, 10]], 12, 'Red') 
canvas.draw_polygon([(50, 70), (80, 40), (30, 90)], 5, 'Blue', 'White') 
canvas.draw_polygon([[90, 70], [80, 40], [70, 90], [70, 70]], 12, 'Yellow', 'Orange') 
frame = simplegui.create_frame('Testing', 100, 100) 
frame.set_draw_handler(draw_handler) 
frame.start() 
# Draw circle on Canvas 
# Syntax: canvas.draw_circle(center_point, radius, line_width, line_color) 
# Syntax: canvas.draw_circle(center_point, radius, line_width, line_color, fill_color = color) 
def draw_handler(canvas): 
canvas.draw_circle((10, 10), 20, 12, 'Green') 
canvas.draw_circle([20, 30], 30, 12, 'Red') 
canvas.draw_circle((50, 50), 20, 5, 'Blue', 'White') 
canvas.draw_circle([70, 80], 30, 10, 'Yellow', 'Orange') 
frame = simplegui.create_frame('Testing', 100, 100) 
frame.set_draw_handler(draw_handler) 
frame.start() 
# Draw point on Canvas 
# Syntax: canvas.draw_point(point, color) 
def draw_handler(canvas): 
canvas.draw_point((10, 10), 'Green') 
canvas.draw_point([20, 30], 'Red') 
frame = simplegui.create_frame('Testing', 100, 100) 
frame.set_draw_handler(draw_handler) 
frame.start() 
# Draw image on Canvas 
# Syntax: canvas.draw_image(image, center_source, width_height_source, center_dest, width_height_dest) 
# Syntax: canvas.draw_image(image, center_source, width_height_source, center_dest, width_height_dest, rotation)
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()
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()
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)
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()
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()
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()
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()
Simple Plot 
SimplePlot provides functions from plotting numeric data – both the x- and y- coordinate values should be numbers. 
# Make a line plot 
# Syntax: simpleplot.plot_lines(framename, width, height, xlabel, ylabel, datasets) 
# Syntax: simpleplot.plot_lines(framename, width, height, xlabel, ylabel, datasets, points) 
# Syntax: simpleplot.plot_lines(framename, width, height, xlabel, ylabel, datasets, points, legends) 
dataset1 = {3: 5, 8: 2, 1: 3} 
dataset2 = [(1, 2), (4, 7), (2, 5), (7, 6)] 
simpleplot.plot_lines('Sample', 400, 300, 'x', 'y', [dataset1, dataset2], True, ['dataset1', 'dataset2']) 
# Make a bar plot 
# Syntax: simpleplot.plot_bars(framename, width, height, xlabel, ylabel, datasets) 
# Syntax: simpleplot.plot_bars(framename, width, height, xlabel, ylabel, datasets, legends) 
dataset1 = {3: 5, 8: 2, 1: 3} 
dataset2 = [(1, 2), (4, 7), (2, 5), (7, 6)] 
simpleplot.plot_bars('Sample', 400, 300, 'x', 'y', [dataset1, dataset2], ['dataset1', 'dataset2']) 
# Make a scatter plot 
# Syntax: simpleplot.plot_scatter(framename, width, height, xlabel, ylabel, datasets) 
# Syntax: simpleplot.plot_scatter(framename, width, height, xlabel, ylabel, datasets, legends) 
dataset1 = {3: 5, 8: 2, 1: 3} 
dataset2 = [(1, 2), (4, 7), (1, 5), (2, 5), (4, 3), (7, 6)] 
simpleplot.plot_scatter('Sample', 400, 300, 'x', 'y', [dataset1, dataset2], ['dataset1', 'dataset2'])
Thanks so much! 
Any questions?

More Related Content

PDF
Learn 90% of Python in 90 Minutes
Matt Harrison
 
PPTX
Python-The programming Language
Rohan Gupta
 
PDF
Matlab and Python: Basic Operations
Wai Nwe Tun
 
PPTX
Introduction to the basics of Python programming (part 3)
Pedro Rodrigues
 
PPTX
Learn python - for beginners - part-2
RajKumar Rampelli
 
PDF
AmI 2015 - Python basics
Luigi De Russis
 
PPTX
Learn python in 20 minutes
Sidharth Nadhan
 
PDF
AmI 2016 - Python basics
Luigi De Russis
 
Learn 90% of Python in 90 Minutes
Matt Harrison
 
Python-The programming Language
Rohan Gupta
 
Matlab and Python: Basic Operations
Wai Nwe Tun
 
Introduction to the basics of Python programming (part 3)
Pedro Rodrigues
 
Learn python - for beginners - part-2
RajKumar Rampelli
 
AmI 2015 - Python basics
Luigi De Russis
 
Learn python in 20 minutes
Sidharth Nadhan
 
AmI 2016 - Python basics
Luigi De Russis
 

What's hot (20)

ODP
Introduction to Python - Training for Kids
Aimee Maree
 
PDF
Begin with Python
Narong Intiruk
 
ODP
Python quickstart for programmers: Python Kung Fu
climatewarrior
 
PDF
Python 101
Prashant Jamkhande
 
PPT
Introduction to Python - Part Two
amiable_indian
 
PPT
Introduction to Python Language and Data Types
Ravi Shankar
 
PPTX
Python language data types
Hoang Nguyen
 
PPTX
Basics of Python programming (part 2)
Pedro Rodrigues
 
PDF
An introduction to Python for absolute beginners
Kálmán "KAMI" Szalai
 
PDF
AmI 2017 - Python basics
Luigi De Russis
 
PDF
python codes
tusharpanda88
 
PPTX
Introduction to the basics of Python programming (part 1)
Pedro Rodrigues
 
PPT
python.ppt
shreyas_test_1234
 
PPTX
Introduction to Python programming
Damian T. Gordon
 
PDF
Python
대갑 김
 
PDF
Python Basics
tusharpanda88
 
PDF
Python Tutorial
Eueung Mulyana
 
PPT
Introduction to Python - Part Three
amiable_indian
 
PPTX
Python
Gagandeep Nanda
 
PPTX
Introduction to Python and TensorFlow
Bayu Aldi Yansyah
 
Introduction to Python - Training for Kids
Aimee Maree
 
Begin with Python
Narong Intiruk
 
Python quickstart for programmers: Python Kung Fu
climatewarrior
 
Python 101
Prashant Jamkhande
 
Introduction to Python - Part Two
amiable_indian
 
Introduction to Python Language and Data Types
Ravi Shankar
 
Python language data types
Hoang Nguyen
 
Basics of Python programming (part 2)
Pedro Rodrigues
 
An introduction to Python for absolute beginners
Kálmán "KAMI" Szalai
 
AmI 2017 - Python basics
Luigi De Russis
 
python codes
tusharpanda88
 
Introduction to the basics of Python programming (part 1)
Pedro Rodrigues
 
python.ppt
shreyas_test_1234
 
Introduction to Python programming
Damian T. Gordon
 
Python
대갑 김
 
Python Basics
tusharpanda88
 
Python Tutorial
Eueung Mulyana
 
Introduction to Python - Part Three
amiable_indian
 
Introduction to Python and TensorFlow
Bayu Aldi Yansyah
 
Ad

Viewers also liked (6)

PPTX
ESCI 452 - Final Project(s)
Paige Bailey
 
PPTX
PyLadies-HTX: First Meetup!
Paige Bailey
 
PPTX
Introduction to Git / Github
Paige Bailey
 
PPTX
I ♥ Maps: Quantum GIS + Python
Paige Bailey
 
PDF
Puppet ile Linux Sistem Yönetimi Otomasyonu
BilgiO A.S / Linux Akademi
 
PPTX
Python 101: Python for Absolute Beginners (PyTexas 2014)
Paige Bailey
 
ESCI 452 - Final Project(s)
Paige Bailey
 
PyLadies-HTX: First Meetup!
Paige Bailey
 
Introduction to Git / Github
Paige Bailey
 
I ♥ Maps: Quantum GIS + Python
Paige Bailey
 
Puppet ile Linux Sistem Yönetimi Otomasyonu
BilgiO A.S / Linux Akademi
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Paige Bailey
 
Ad

Similar to Python 101++: Let's Get Down to Business! (20)

PPTX
Python Workshop
Assem CHELLI
 
PDF
Python Part 1
Mohamed Ramadan
 
PPT
Python course in_mumbai
vibrantuser
 
PPT
Python course in_mumbai
vibrantuser
 
PPT
ComandosDePython_ComponentesBasicosImpl.ppt
oscarJulianPerdomoCh1
 
PPTX
Chapter - 2.pptx
MikialeTesfamariam
 
PPTX
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
PDF
Processing data with Python, using standard library modules you (probably) ne...
gjcross
 
PPTX
python_computer engineering_semester_computer_language.pptx
MadhusmitaSahu40
 
PDF
ppt_pspp.pdf
ShereenAhmedMohamed
 
PDF
Python Cheatsheet_A Quick Reference Guide for Data Science.pdf
zayanchutiya
 
PPTX
Python bible
adarsh j
 
PPTX
Learning python
Harry Potter
 
PPTX
Learning python
Tony Nguyen
 
PPTX
Learning python
Luis Goldster
 
PPTX
Learning python
Hoang Nguyen
 
PPTX
Learning python
James Wong
 
PPTX
Learning python
Young Alista
 
PPTX
Learning python
Fraboni Ec
 
PDF
Introduction to Python
UC San Diego
 
Python Workshop
Assem CHELLI
 
Python Part 1
Mohamed Ramadan
 
Python course in_mumbai
vibrantuser
 
Python course in_mumbai
vibrantuser
 
ComandosDePython_ComponentesBasicosImpl.ppt
oscarJulianPerdomoCh1
 
Chapter - 2.pptx
MikialeTesfamariam
 
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
Processing data with Python, using standard library modules you (probably) ne...
gjcross
 
python_computer engineering_semester_computer_language.pptx
MadhusmitaSahu40
 
ppt_pspp.pdf
ShereenAhmedMohamed
 
Python Cheatsheet_A Quick Reference Guide for Data Science.pdf
zayanchutiya
 
Python bible
adarsh j
 
Learning python
Harry Potter
 
Learning python
Tony Nguyen
 
Learning python
Luis Goldster
 
Learning python
Hoang Nguyen
 
Learning python
James Wong
 
Learning python
Young Alista
 
Learning python
Fraboni Ec
 
Introduction to Python
UC San Diego
 

Recently uploaded (20)

PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PPTX
Simple and concise overview about Quantum computing..pptx
mughal641
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Software Development Methodologies in 2025
KodekX
 
PDF
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
PDF
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
PDF
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PDF
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PPTX
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
PPTX
Introduction to Flutter by Ayush Desai.pptx
ayushdesai204
 
PDF
AI-Cloud-Business-Management-Platforms-The-Key-to-Efficiency-Growth.pdf
Artjoker Software Development Company
 
PPTX
IT Runs Better with ThousandEyes AI-driven Assurance
ThousandEyes
 
PPTX
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
PDF
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
Simple and concise overview about Quantum computing..pptx
mughal641
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Software Development Methodologies in 2025
KodekX
 
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
Doc9.....................................
SofiaCollazos
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
Introduction to Flutter by Ayush Desai.pptx
ayushdesai204
 
AI-Cloud-Business-Management-Platforms-The-Key-to-Efficiency-Growth.pdf
Artjoker Software Development Company
 
IT Runs Better with ThousandEyes AI-driven Assurance
ThousandEyes
 
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 

Python 101++: Let's Get Down to Business!

  • 1. Python 101++ Let’s Get Down to Business! PyTexas 2014
  • 2. Just as a refresher…
  • 3. Data Types  Integers  Floating-point numbers  Booleans  Strings  Tuples  Lists  Dictionaries 42 3.1416 True “Gig ‘em!” (27.174885 , 78.039794) [“Ian”, “Kevin”, Curtis”] {1: ‘a’, 2: ‘b’, 9: ‘c’}
  • 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()
  • 8. Booleans and, or, not, any, all
  • 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
  • 11. Interacting with CodeSkulptor  Run  Save  Fresh URL  Open Local  Reset
  • 12. Additional Resources  Docs (documentation)  Demos  Viz Mode
  • 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
  • 31. str() Converts values into a string. print str() print str(4859202) print str(True) print str(‘abc’) print str(None) print str([1, 2, 3, 4, 5]) print str((1, 2, 3, 4, 5)) print str({1: ‘a’, 2: ‘b’, 3: ‘c’}) print str(set([1, 2, 3, 4, 5])) print str(str) # the empty string 4859202 True abc None (1, 2, 3, 4, 5) [1, 2, 3, 4, 5] {1: ‘a’, 2: ‘b’, 3: ‘c’} set([1, 2, 3, 4, 5]) <class ‘str’>
  • 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
  • 34. str.find(), str.index(), and str.replace() Finds a substring; replaces a substring. print ‘abcdabcd’.find(‘bc’) print ‘abcdabcd’.find(‘bc’, 3) print ‘abcdabcd’.rfind(‘bc’) print ‘abcdabcd’.rfind(‘bc’, 3) print ‘abcdabcd’.find(‘f’) print ‘abcdabcd’.rfind(‘f’) print ‘abcdabcd’.find(‘bc’, 6) print ‘abcdabcd’.rfind(‘bc’, 6) print ‘abcdabcd’.find(‘bc’, 3, 6) print ‘abcdabcd’.replace(‘bc’, ‘f’) print ‘abcdabcd’.replace(‘bc’, ‘f’, 1) print ‘abcdabcd’.replace(‘g’, ‘f’) print ‘aaaaa’.replace(‘aa’, ‘f’) 1 5 5 5 -1 -1 -1 -1 -1 afdafd afdabcd abcdabcd ffa
  • 35. str.startswith(), str.endswith(), and str.isdigit() Checks prefix; checks suffix; checks whether the string contains a digit. print ‘silly string’.startswith(‘sil’) print ‘silly string’.startswith(‘ing’) print ‘silly string’.endswith(‘sil’) print ‘silly string’.endswith(‘ing’) print ‘’.isdigit() print ‘1234’.isdigit() print ‘1234abc’.isdigit() print ' cde fgh '.strip() print ' cde fgh '.strip(None) print ‘aaababcdeafghbaba'.strip(‘ab’) print ' cde fgh '.lstrip() print ‘aaababcdeafghbaba’.strip() print ' cde fgh '.rstrip() print ‘aaababcdeafghbaba’.strip() True False False True False True False cde fgh cde fgh cdeafgh cde fgh cdeafghbaba cde fgh aaababcdeafgh
  • 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
  • 42. Sequences: slicing and counting list[i:j:k], list.count() print ‘abcde’[1:3] print (8, 2, 4, 0)[1:-1] print [8, 2, 4, 0][1:] print 'abcde'[1:4:2] print (8, 2, 4, 0)[1::1] print [8, 2, 4, 0][::-1] print ['a', 'b', 'c', 'b', 'a', 'c'].count('b') print ('a', 'b', 'c', 'b', 'a', 'c').count('b') print 'abcbac'.count('c') print 'abcbac'.count('cb') print ['a', 'b', 'c', 'b', 'a', 'c'].count('b', 3) print ('a', 'b', 'c', 'b', 'a', 'c').count('b', 3) print 'abcbac'.count('b', 3) print ['a', 'b', 'c', 'b', 'a', 'c'].count('b', 2, 3) print ('a', 'b', 'c', 'b', 'a', 'c').count('b', 2, 3) print 'abcbac'.count('b', 2, 3) bc (2, 4) [2, 4, 0] bd (2, 4, 0) [0, 4, 2, 8] 2 2 2 1 1 1 1 0 0 0
  • 44. in, not in, and len() Tests if an item is in an iterable or not; tests the length of the iterable. print 8 in [1, 2, 3, 4, 5, 6, 7] print 'c' in 'abcde‘ print (1,3) in ('a', 3, 4, (1,2), 'hello') print 3 in {1: 'a', 2: 'b', 3: 'c'} print 3 in {'a': 1, 'b': 2, 'c: 3} print 8 in set([1, 2, 3, 4, 5, 6, 7]) print 8 not in [1, 2, 3, 4, 5, 6, 7] print 'c' not in 'abcde’ print (1,3) not in ('a', 3, 4, (1,2), 'hello') print 3 not in {1: 'a', 2: 'b', 3: 'c'} print 3 not in {'a': 1, 'b': 2, 'c: 3} print 8 not in set([1, 2, 3, 4, 5, 6, 7]) print len('') print len([2, 35, -2, 12]) print len((2, 35, -2, 12)) print len({1: 2, 3: 4}) print len(set([2, 35, -2, 12])) False True False True False False True False True False True True 0 4 4 2 4
  • 45. sum(), max(), and min() Sum of elements in an iterable; maximum and minimum value among multiple inputs or in iterable. print sum([10, 20, 30]) print sum((10, 20, 30)) print sum({1: 10, 2: 20}) print sum(set([10, 20, 30)])) print sum([10, 20, 30], 2) print max(2, 35, -2, 12) print max('c', 'x', 'cat', 'father') print max([2, 35, -2, 12]) print max(['c', 'x', 'cat', 'father']) print max((2, 35, -2, 12)) print max({1: 2, 3: 4}) print max(set([2, 35, -2, 12])) print min(2, 35, -2, 12) print min('c', 'x', 'cat', 'father') print min([2, 35, -2, 12]) print min(['c', 'x', 'cat', 'father']) print min((2, 35, -2, 12)) print min({1: 2, 3: 4}) print min(set([2, 35, -2, 12])) 60 60 3 60 62 35 x 35 x 35 3 35 -2 c -2 c -2 1 -2
  • 46. zip() and map() Combines the ith elements of iterables into tuples; applies a function to iterable elements. print zip('abcd', '1234', (5, 6, 7, 8)) print zip([1, 2, 3, 4], ['a', 'b', 'c']) print zip({1: 2, 3: 4}, set([5, 6])) print zip([1, 2, 3]) print zip() list1 = ['a', 'b', 'c', 'd', 'e'] list2 = ['z', 'y', 'x', 'w', 'v'] for letter1, letter2 in zip(list1, list2): print letter1 + letter2 zipped_list = [(1, 'a'), (2, 'b'), (3, 'c')] first_elts, second_elts = zip(*zipped_list) print first_elts print second_elts def square(n): return n * n print map(square, [3, 7, 1]) [('a', '1', 5), ('b', '2', 6), ('c', '3', 7), ('d', '4', 8)] [(1, 'a'), (2, 'b'), (3, 'c')] [(1, 5), (3, 6)] [(1,), (2,), (3,)] [] az by cx dw ev [1, 2, 3] ['a', 'b', 'c'] [9, 49, 1]
  • 47. filter() and reduce() Filters iterable’s elements into a sequence; combines iterable’s elements by applying a function. def is_positive(n): return n > 0 print filter(is_positive, [3, -7, 1]) def is_positive(n): return n > 0 print filter(is_positive, (3, -7, 1)) def is_aorb(x): return x == 'a' or x == 'b' print filter(is_aorb, 'acdba') def is_positive(n): return n > 0 print filter(is_positive, set([3, -7, 1])) print filter(None, [set(), 3, {}, 0, False, '', -1, []) def add(x, y): return x + y print reduce(add, [3, -7, 1]) def add(x, y): return x + y print reduce(add, (3, -7, 1), 12) def maximum(x, y): if x >= y: return x else: return y print reduce(maximum, 'acdba', 'a') def maximum(x, y): if x >= y: return x else: return y print reduce(maximum, 'acdba', 'z') def second(x, y): return y print reduce(second, [1, 2, 3, 4, 5]) [3,1] (3,1) ‘aba’ [1,3] [3,-1] -3 9 ‘d’ ‘z’ 5
  • 48. Sets
  • 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’)])
  • 50. set.union(), set.intersection(), set.difference, set.symmetric_difference() print set([1, 2, 3, 4, 5]).union(set([5, 6, 7])) print set([1, 2, 3, 4, 5]).intersection(set([5, 6, 7])) print set([1, 2, 3, 4, 5]).difference(set([5, 6, 7])) print set([1, 2, 3, 4, 5]).symmetric_difference(set([5, 6, 7])) # With mutations s = set([1, 2, 3, 4, 5]) s.update(set([5, 6, 7])) print s s = set([1, 2, 3, 4, 5]) s.intersection_update(set([5, 6, 7])) print s s = set([1, 2, 3, 4, 5]) s.difference_update(set([5, 6, 7])) print s s = set([1, 2, 3, 4, 5]) s.symmetric_difference_update(set([5, 6, 7])) print s set([1, 2, 3, 4, 5, 6, 7]) set([5]) set([1, 2, 3, 4]) set([1, 2, 3, 4, 6, 7]) set([1, 2, 3, 4, 5, 6, 7]) set([5]) set([1, 2, 3, 4]) set([1, 2, 3, 4, 6, 7])
  • 51. set.add(), set.remove(), set.discard(), set.pop() Adds an element in a set; removes specified or arbitrary item from a set. s = set([1, 2, 3, 4, 5]) s.add(5) print s s.add(6) print s s = set([1, 2, 3, 4, 5]) s.remove(5) print s s.discard(7) print s s.discard(3) print s s = set([1, 2, 3, 4, 5]) print s.pop() print s set([1, 2, 3, 4, 5]) set([1, 2, 3, 4, 5, 6]) set([1, 2, 3, 4]) set([1, 2, 3, 4]) set([1, 2, 4]) 1 set([2, 3, 4, 5])
  • 52. set.issubset(), set.issuperset(), set.copy() Tests for subsets and supersets; copies a set. print set([2, 9, 7, 1].issubset(s) print set([2, 9, 7, 1].issubset(set([1, 7])) print set([2, 9, 7, 1].issubset(set([1, 2, 3, 4])) print set([2, 9, 7, 1].issubset(set([1, 2, 3, 4, 5, 6, 7, 8, 9])) print set([2, 9, 7, 1].issuperset(s) print set([2, 9, 7, 1].issuperset(set([1, 7])) print set([2, 9, 7, 1].issuperset(set([1, 2, 3, 4])) print set([2, 9, 7, 1].issuperset(set([1, 2, 3, 4, 5, 6, 7, 8, 9])) s = set([1, 2, 3, 4, 5]) t = s.copy() print s == t print s is t True False False True True True False False True False
  • 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()
  • 58. Canvas, ctd. The canvas is where you can draw text and shapes. # Draw polygon on Canvas # Syntax: canvas.draw_polygon(point_list, line_width, line_color) # Syntax: canvas.draw_polygon(point_list, line_width, line_color, fill_color = color) def draw_handler(canvas): canvas.draw_polygon([(10, 20), (20, 30), (30, 10)], 12, 'Green') canvas.draw_polygon([[30, 20], [40, 40], [50, 20], [10, 10]], 12, 'Red') canvas.draw_polygon([(50, 70), (80, 40), (30, 90)], 5, 'Blue', 'White') canvas.draw_polygon([[90, 70], [80, 40], [70, 90], [70, 70]], 12, 'Yellow', 'Orange') frame = simplegui.create_frame('Testing', 100, 100) frame.set_draw_handler(draw_handler) frame.start() # Draw circle on Canvas # Syntax: canvas.draw_circle(center_point, radius, line_width, line_color) # Syntax: canvas.draw_circle(center_point, radius, line_width, line_color, fill_color = color) def draw_handler(canvas): canvas.draw_circle((10, 10), 20, 12, 'Green') canvas.draw_circle([20, 30], 30, 12, 'Red') canvas.draw_circle((50, 50), 20, 5, 'Blue', 'White') canvas.draw_circle([70, 80], 30, 10, 'Yellow', 'Orange') frame = simplegui.create_frame('Testing', 100, 100) frame.set_draw_handler(draw_handler) frame.start() # Draw point on Canvas # Syntax: canvas.draw_point(point, color) def draw_handler(canvas): canvas.draw_point((10, 10), 'Green') canvas.draw_point([20, 30], 'Red') frame = simplegui.create_frame('Testing', 100, 100) frame.set_draw_handler(draw_handler) frame.start() # Draw image on Canvas # Syntax: canvas.draw_image(image, center_source, width_height_source, center_dest, width_height_dest) # Syntax: canvas.draw_image(image, center_source, width_height_source, center_dest, width_height_dest, rotation)
  • 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()
  • 66. Simple Plot SimplePlot provides functions from plotting numeric data – both the x- and y- coordinate values should be numbers. # Make a line plot # Syntax: simpleplot.plot_lines(framename, width, height, xlabel, ylabel, datasets) # Syntax: simpleplot.plot_lines(framename, width, height, xlabel, ylabel, datasets, points) # Syntax: simpleplot.plot_lines(framename, width, height, xlabel, ylabel, datasets, points, legends) dataset1 = {3: 5, 8: 2, 1: 3} dataset2 = [(1, 2), (4, 7), (2, 5), (7, 6)] simpleplot.plot_lines('Sample', 400, 300, 'x', 'y', [dataset1, dataset2], True, ['dataset1', 'dataset2']) # Make a bar plot # Syntax: simpleplot.plot_bars(framename, width, height, xlabel, ylabel, datasets) # Syntax: simpleplot.plot_bars(framename, width, height, xlabel, ylabel, datasets, legends) dataset1 = {3: 5, 8: 2, 1: 3} dataset2 = [(1, 2), (4, 7), (2, 5), (7, 6)] simpleplot.plot_bars('Sample', 400, 300, 'x', 'y', [dataset1, dataset2], ['dataset1', 'dataset2']) # Make a scatter plot # Syntax: simpleplot.plot_scatter(framename, width, height, xlabel, ylabel, datasets) # Syntax: simpleplot.plot_scatter(framename, width, height, xlabel, ylabel, datasets, legends) dataset1 = {3: 5, 8: 2, 1: 3} dataset2 = [(1, 2), (4, 7), (1, 5), (2, 5), (4, 3), (7, 6)] simpleplot.plot_scatter('Sample', 400, 300, 'x', 'y', [dataset1, dataset2], ['dataset1', 'dataset2'])
  • 67. Thanks so much! Any questions?