Intro to
Programming
with Python

Fall 2011
course
navigation

sep 20

question

Here's an example of table formatting: from math import sqrt print " %10s %10s " % ("n", "sqrt(n)") print " %10s %10s " % ("-"*10, "-"*10) for n in range(20): print " %10i %10.4f " % (n, sqrt(n))

chap 5 : exploring "objects" with a graphics API

This is usually a fun week ...

objects

Object oriented programming is a popular paradigm these days. It's not the only one, but it's an important one.
An "object" is a abstration chunk of data (a "thing") with actions (called "methods") it can perform.
A "class" is a kind of object. Example: Point, Circle, GraphWin
An "instance" is a specific object: Example: that red circle right there.
In python, creating an instance is done this way : p = Point(10, 20) # instance_variable = ClassName(argument1, arg2)
And once we have one, we can tell it do things like this: p.move(2, 3) # change position (x,y)=(10,20) to (12,23)
An "API" (Application Programmer's Interface) is a description of which sorts of objects you can create, and what methods they have.
All this is pretty abstract, so let's see a concrete example with the attached files.

graphics.py

See the resources or Zelle's book page for both (1) the file you'll need to run this stuff (put in in the same directory), and (2) the API of what you can do with it.
Stuff to play around with interactively class:
... and so on
Tic Tac Toe, anyone ?

in class

# wiggle.py # # in class demo of Zelle's graphic library # # # new python functions: # # from random import randint # randint(low, high) low <= random num <= high # # from time import sleep # sleep(2) do nothing for 2 sec # from graphics import * from time import sleep from random import randint def main(): window = GraphWin("wiggle", 300, 300) dot = Circle(Point(150,150), 20) dot.setFill("red") dot.draw(window) for i in range(100): dx = randint(-5, 5) # pixels dy = randint(-5, 5) dot.move(dx, dy) sleep(0.1) # in seconds wait = window.getClick() main()
Color names : http://www.w3schools.com/html/html_colornames.asp
http://cs.marlboro.edu/ courses/ fall2011/python/ notes/ sep_20
last modified Tuesday September 20 2011 11:14 am EDT

attachments [paper clip]

     name last modified size
   graphics.py Sep 20 2011 3:12 am 28.8kB    graphics.pyc Sep 20 2011 3:13 am 38.2kB    triangle.py Sep 20 2011 3:12 am 760B