«

»

Function Example: Assignment 2

A good example of how to use functions is a modified version of assignment 2, available here.

In this example, we created a few helper functions, like the ones below to convert values between cartesian values and screen coordinates

#convert an x value from cartesian coordinates to screen coordinates
def cartx(x):
	x = scale * x
	x = xcenter + x
	return x

#convert an x value from cartesian coordinates to screen coordinates
def carty(y):
	y = scale * y
	y = ycenter - y
	return y

The core of the program, that is, the drawing of the curve was also done using functions, as seen here

#Draw the curve defined by a,b,c and d from a beginning cartesian value to an end cartesian value
#approximating by delta cartesian units
def draw(a,b,c,d,begin,end,delta):
	x = begin
	while x < end:
		y = formula(a,b,c,d,x)
		y2 = formula(a,b,c,d,x+delta)

		print "line",cartx(x),carty(y),cartx(x+delta),carty(y2)

		x = x + delta
	sys.stdout.flush()

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>