7.3 Using Variables in Functions

Recall that functions give us a mechanism by which we can encapsulate algorithms. Since variables are very useful for writing almost any kind of algorithm, we can certainly use variables in functions:

In the preceding program’s draw() function, we associate variable size with a value of 10. We then make a function call to ellipse() using the value of the size variable as both the 3rd and 4th arguments in the function call. This is the same as just calling ellipse(100, 100, 10, 10), since we gave size a value of 10.

Since the purpose of functions is encapsulation, any variables that we use as part of a function are only visible to that function. For example, the following code will result in an error:

Since the size variable is assigned a value in the setup() function, when we try to use it in the draw() function, Python will complain that draw() doesn’t know anything about a variable called size.

Finally, it’s worth noting that function parameters, which we already learned about, are also really just variables with one special property: when the function is called, the parameter variables are automatically initialized with the argument values that were used in the function call. After that, they’re just normal variables in every way. The following program re-uses a function parameter for drawing a donut (a circle within a circle):

Notice how in the program above, we were able to change the value associated with the size variable by setting it to one-half of its original value and then use it again in the second function call to ellipse().