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

  • Published on
    19-Jun-2015

  • View
    437

  • Download
    0

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

  • 1. Python 101++Lets Get Down to Business!PyTexas 2014

2. Just as a refresher 3. Data Types Integers Floating-point numbers Booleans Strings Tuples Lists Dictionaries423.1416TrueGig em!(27.174885 , 78.039794)[Ian, Kevin, Curtis]{1: a, 2: b, 9: c} 4. for LoopsBeatles = [John, Paul, George, Ringo]for Beatle in Beatles:print BeatleJohnPaulGeorgeRingo 5. while Loopstemperature = 115while temperature > 112:print(temperature)temperature = temperature 1print The coffee is cool enough to drink. 6. Conditionals (if elif else)>>> x = int(raw_input(Please enter the answer to life, theuniverse, and everything: ))Please enter the answer to life, the universe, and everything:42>>> if x < 0:x = 0print Negative changed to zero.elif x == 0:print Zeroelif x == 1:print Singleelse:print MoreMore 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. Booleansand, or, not, any, all 9. CodeSkulptor! 10. CodeSkulptor Developed by Scott Rixner of RiceUniversity to use for COMP 200. Based on CodeMirror and Skulpt. www.codeskulptor.org If you want to learn more aboutusing Python with CodeSkulptorafter this class, check out theCoursera course An Introductionto Interactive Programming inPython! (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 13. Objects 14. ObjectsIn 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 anobject are called methods. Words that describe an objectare called attributes. 15. ObjectsIf this truly spectacular car was an object namedmyCar, it might have these attributes:myCar.colormyCar.maxspeedmyCar.electricityUsagemyCar.weightmyCar.priceYou can display them:print myCar.priceYou can assign values to them:myCar.color = redYou can assign them to attributes in other objects:anotherCar.color = myCar.color 16. 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 areincluded inside the object. 17. ObjectsIn Python, a class is like a description orblueprint of an object.class Tesla:color = redsize = full-sizetype = luxurymanufacturer = Tesla_Motorsdirection = def drive(self_in_circles):if self.direction == north:self.direction == westelif self.direction == west:self.direction == southelif self.direction == south:self.direction == eastelse:self.direction == north 18. Modules 19. Modules A module is a block of code that can be combined with other blocks to build aprogram. You can use different combinations of modules to do different jobs, just likeyou 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 Theres no reason to invent the wheel! If someone has created a module thataccomplishes a specific task you needed to accomplish, theres no reason foryou to put forth the effort. 20. Modules Generate a random numberbetween 1 100: Raise 2 to the power of 3 Get the current time Find the first match, if any, of theregular expression pattern in thegiven 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(rZZZ, PyTexas 2014!)None 21. Types and Operations 22. List Methods 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 listprint [1, 2, 3, 8, 9] # a list of numbersprint [(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]01234 25. list.append() and list.extend()Adds item to the end of the list; and adds multiple items to the end of a lista_list = [1, 2, 3]a_list.append(4)a_list.append([5, 6, 7])print a_listlist1 = [1, 2, 3]list2 = [1, 2, 3]list1.append([4, 5, 6])list2.extend([4, 5, 6])print list1print list2a_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_lista_list.insert(0, 'y')print a_lista_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_lista_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(), itdefaults 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_lista_list = [2, 1, 3, 2]a_list.sort()print a_listprint 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)] 29. String Methods 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 isa multi-linestring.' single quote character" double quote character backslash characterb backspace characterf formfeed charactern new line character (starts a new line)r carriage return charactert 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 string4859202TrueabcNone(1, 2, 3, 4, 5)[1, 2, 3, 4, 5]{1: a, 2: b, 3: c}set([1, 2, 3, 4, 5]) 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,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] 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()PearABC123DEFabc123def 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)1555-1-1-1-1-1afdafdafdabcdabcdabcdffa 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()TrueFalseFalseTrueFalseTrueFalsecde fghcde fghcdeafghcde fghcdeafghbabacde fghaaababcdeafgh 36. Dictionary Methods 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 anyimmutable (unchangeable) type. When printed, iterated upon, or converted into a sequence, a dictionarys elements willappear 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] = 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 dd[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'} 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 dd = {1: 'a', 2: 'b', 3: 'c'}print d.pop(1, 'xyz')print dd = {1: 'a', 2: 'b', 3: 'c'}print d.pop(4)print dd = {1: 'a', 2: 'b', 3: 'c'}print d.pop(4, 'xyz')print dTrueFalsea{2: 'b', 3: 'c'}a{2: 'b', 3: 'c'}Line 2: KeyError: 4xyz{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', valueprint {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 thedictionary'[(1, 'a'), (2, 'b'), (3, 'c')]1 maps to a2 maps to b3 maps to c[1, 2, 3]['a', 'b', 'c']a is a value in the dictionaryb is a value in the dictionaryc is a value in the dictionary 41. Sequences 42. 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 43. Iterables 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 'abcdeprint (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 'abcdeprint (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]))FalseTrueFalseTrueFalseFalseTrueFalseTrueFalseTrueTrue04424 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]))60603606235x35x35335-2c-2c-21-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 + letter2zipped_list = [(1, 'a'), (2, 'b'), (3, 'c')]first_elts, second_elts = zip(*zipped_list)print first_eltsprint second_eltsdef square(n):return n * nprint 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,)][]azbycxdwev[1, 2, 3]['a', 'b', 'c'][9, 49, 1] 47. filter() and reduce()Filters iterables elements into a sequence; combines iterables elements by applying a function.def is_positive(n):return n > 0print filter(is_positive, [3, -7, 1])def is_positive(n):return n > 0print 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 > 0print filter(is_positive, set([3, -7, 1]))print filter(None, [set(), 3, {}, 0, False, '', -1, [])def add(x, y):return x + yprint reduce(add, [3, -7, 1])def add(x, y):return x + yprint reduce(add, (3, -7, 1), 12)def maximum(x, y):if x >= y: return xelse: return yprint reduce(maximum, 'acdba', 'a')def maximum(x, y):if x >= y: return xelse: return yprint reduce(maximum, 'acdba', 'z')def second(x, y):return yprint reduce(second, [1, 2, 3, 4, 5])[3,1](3,1)aba[1,3][3,-1]-39dz5 48. Sets 49. set() A set is an unordered collection without duplicates. When printed, iterated upon, or converted into a sequence, its elements willappear 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 mutationss = set([1, 2, 3, 4, 5])s.update(set([5, 6, 7]))print ss = set([1, 2, 3, 4, 5])s.intersection_update(set([5, 6, 7]))print ss = set([1, 2, 3, 4, 5])s.difference_update(set([5, 6, 7]))print ss = set([1, 2, 3, 4, 5])s.symmetric_difference_update(set([5, 6, 7]))print sset([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 ss.add(6)print ss = set([1, 2, 3, 4, 5])s.remove(5)print ss.discard(7)print ss.discard(3)print ss = set([1, 2, 3, 4, 5])print s.pop()print sset([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])1set([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 == tprint s is tTrueFalseFalseTrueTrueTrueFalseFalseTrueFalse 53. Graphics Modules 54. 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 frames background color# Syntax: frame.set_canvas_background(color)frame = simplegui.create_frame('Testing', 100, 100)frame.set_canvas_background('Red')frame.start()# Start frames interactivityframe = simplegui.create_frame('Testing', 100, 100)frame.start()# Get Canvas Texts 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 ObjectsControl objects are placed in the control panel, which is the left-hand part of the frame. They are placed top-downin 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-downin 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. 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() 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. 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():passtimer = simplegui.create_timer(100, timer_handler)print timer.is_running()timer.start()print timer.is_running()timer.stop()print timer.is_running() 60. 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 images width# Syntax: image.get_width()# Get images height# Syntax: image.get_height() 61. 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 sounds volume# Syntax: sound.set_volume()sound = simplegui.load_sound('http://commondatastorage.googleapis.com/codeskulptor-assets/Epoq-Lepidoptera.ogg')sound.set_volume(0.7) 62. MapsSimpleMap module provides an interface for drawing and annotating maps. The underlying maps are provided by GoogleMaps. 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 GoogleMaps. 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. 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() 65. LinesA line object corresponds to a drawn path between two markers on the map. The path follows the available streets on themap. 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 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']) 67. Thanks so much!Any questions?