python 101++: let's get down to business!

Post on 19-Jun-2015

455 Views

Category:

Technology

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

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!

TRANSCRIPT

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

JohnPaulGeorgeRingo

while Loopstemperature = 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()

Booleansand, 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.

ObjectsIf this truly spectacular car was an object named myCar, it might have these attributes:

myCar.colormyCar.maxspeedmyCar.electricityUsagemyCar.weightmyCar.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

ObjectsThe 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 isa multi-linestring.”””

\' 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 string4859202TrueabcNone(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,da bc dazzbczzda ba 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

ABC123DEFabc123def

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’)

1555-1-1-1-1-1

afdafdafdabcdabcdabcdffa

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()

TrueFalse

FalseTrue

FalseTrueFalse

cde fghcde fghcdeafghcde fghcdeafghbaba cde fghaaababcdeafgh

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] = valueConverts 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’}

bbNonenot 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

TrueFalse

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 countinglist[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]

2221111000

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]))

FalseTrueFalseTrueFalseFalse

TrueFalseTrueFalseTrueTrue

04424

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]))

606036062

35x35x35335

-2c-2c-21-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 mutationss = 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

TrueFalseFalseTrue

TrueTrueFalseFalse

TrueFalse

Graphics Modules

FrameA 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 interactivityframe = 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 ObjectsControl 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()

CanvasThe 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)

TimersA 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()

ImagesAn 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()

SoundsA 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)

MapsSimpleMap 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()

MarkersA 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()

LinesA 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 PlotSimplePlot 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?

top related