Week 5: Nested Loops, Object Orient Programming, Graphics Library
Week 5 Goals
-
Practice with nested loops
-
Learn to program using objects in Python
-
Learn to use the Graphics Library to create graphical programs
-
More practice with functions
Get Week 5 In-class Code
To copy over the week 5 in-class example programs, do the following (If you have trouble with either of these steps, ask a Ninja or your professor for help):
-
Create a w05-graphics subdirectory in your
cs21/inclass
directory, and cd into it:$ cd ~/cs21/inclass $ mkdir w05-graphics $ cd w05-graphics $ pwd /home/yourusername/cs21/inclass/w05-graphics
-
Copy over the week 5 files into your
w05-graphics
subdirectory (check that they copied successfully copied by runningls
:$ cp ~admin21/public/w05-graphics/*.py ./ $ ls animate.py bullseye.py nested.py objects.py playground.py setcoords.py
Week 5 Code
-
nested.py
: examples and practice with nested loops. -
objects.py
: examples with strings and lists as objectsSection 10.6 of the textbook shows some example list and str method functions.
You can list all the methods of str and list class by running python3 in interactive mode, and then run
help(str)
,help(list)
(note that the documentation is a bit difficult to decipher at first):python3 >>> help(list) >>> help(str) >>> done()
-
playground.py
: a first example of using the Graphics library, creating different shape objects and drawing them to the graphics window. -
bullseye.py
: another graphics library example, with a function you can try writing to draw a bullseye pattern to the graphics window. -
setcoords.py
: an example using thesetCoords
method of theGraphWin
class to change the x and y coordinate ranges of the graphics window. There are some functions to try out drawing things to theGraphWin
basedsetCoords
changes to the x and y axis range.This also includes some examples of using functions from the
Random
library. -
animate.py
: some examples moving graphics objects and creating animations using the graphics library.
Editing and Running Python programs
To open and edit a Python source code file, in a terminal, run the
code
editor with the name of the file you want to edit (e.g., prog.py
):
$ code prog.py
To run a Python program, in a terminal, invoke the Python
interpreter (python3
) followed by the name of the file with the
Python program you want to run (e.g. prog.py
):
$ python3 prog.py