Return values
Use your draw_circle function again, but this time add information about the mathematical properties of the circles that are drawn.
One use for return values is to provide the result of a calculation. You’re going to add a function to calculate the area of a circle from the radius.
Note: The equation for the area of a circle is πr2 where r is the radius.
You could use a rough approximation for pi in this equation, but you can also use a useful Python module called math.
To use it, you have to import the math module at the top of your program, like so:
import math
You can then use it in a function that returns the area of a circle when given a radius (r):
def circle_area(r):
return math.pi * r * r
Now you can call this function whenever you need to calculate the area of a circle. Putting this code into a function with a return value means that you don’t have to retype the calculation code each time you need to use it. It’s also less error prone, as you can write and test the code once and make sure it works. And if you find a better way to do a calculation, then you only need to update the calculation code in one place.
Note: If you are using a function with a return, you must make sure that you are assigning it to a variable in the main code. The value returned by the function will then be stored in that variable. In the code below I am using the area variable to store the return value from the function circle_area(10).
area = circle_area(10)
Next, change the draw_circle function so that, when it draws a circle, it also calls the circle_area function and writes the area on the circle. The pen will need to be in a different colour so you can see it; you can just use black for now. (Your code may look a bit different, depending which activities you completed in the previous step.)
def draw_circle(t_name, r, col):
t_name.color(col)
t_name.dot(2 * r)
t_name.color("black")
t_name.write("Area: " + str(circle_area(r)), align="center")