CSci 157 - Lab 8
Purpose: the main objective is to learn how to use functions to structure programs...and our thinking.
Part 1. Flow of Control
- Test your understanding by visiting this
webpage. Together with your partner, read through the Flow
of Control Summary and try the two Check your understanding
problems.
Hopefully you get these right the first time!
- Turn in the results to the instructor.
Part 2. Working with Functions
In this section, we'll modify a program developed in previous labs to use functions. To start out:
- Download the program voting.py. Run it several times to make sure it works for clicks on the two rectangles, or in no rectangle.
- Consider the code for determining if a
Point
is inside anRectangle
:if ((maybe.getX() > 10 and maybe.getX() < 80) and (maybe.getY() > 10 and maybe.getY() < 80)): print('Voted for Yellow rect.') elif ((maybe.getX() > 260 and maybe.getX() < 330) and (maybe.getY() > 10 and maybe.getY() < 80)): print('Voted for Purple rect.')
This part of the program works now, but what if someone decides the rectangles should be moved, they aren't large enough for people with vision problems (an accessibility issue), or change them for some aesthetic reason? Will the x- and y-coordinates we hard-coded into this selection statement still work? Probably not.
To protect ourselves from later changes, it would be better to not use numbers directly in the code like this. Instead, we can use theRectangle
methods provided to return thePoint
objects that represent the corners, and get the coordinates directly from those.
- Switch driver and observer for this part.
Another change that improves the design of this and future programs is to notice that determining if a mouse click occurs inside an object in the window happens all the time, in many different programs. Rectangles make great labeled buttons, after all. So the code for determining if aPoint
is inside anRectangle
is a common pattern, and we should abstract it by making it a function. The function can them be reused in other programs that need the same functionality.
Make a new functionrect_contains
that, given aPoint
and aRectangle
as parameters, returnsTrue
if thePoint
is inside theRectangle
, andFalse
otherwise. You can move the selection statement out of main and into the body of the new function, but you will need to make a few modifications. Be sure to define this function before the definition of main.
- Modify
main
to call this function in place of the checks it did before, and make sure the program works as before.
-
Instead of printing the 'Voted for...' information in the function, it should return just the string representing the color. The print function can then move to main,
Reminder - always do this at the end of labs
Make sure both team members have a copy of the program developed in this lab.