A9 - Creating Your Own Functions
In Python (and most programming languages), a function is just a subprogram that contains a return statement. Here's a quick example:
Connecting this to what we already know about functions:
- The inputs are the function arguments (in this case
aandb) - The output is what the function returns
- The rule is the code contained in the subprogram
When a subprogram has a return statement (thereby making it a function), we can call that function anywhere we would normally put a variable, and the value of the function call will become whatever gets returned. For example:
For your first task, we are going to revisit some of the geometry formulas you worked with earlier in the course, but this time we are going to make them into functions. Something like this:
# This function calculates the area of a rectangle with the given dimensions
def areaOfRect(width, height):
return width * height
# This function calculates the area of a circle with the given radius
def areaOfCircle(radius):
return 3.14 * radius * radius
# Now, let's suppose we had a diagram consisting of the following:
#
# - A 5x3 rectangle
# - A 2x8 rectangle
# - A circle with radius 5
# - A circle with radius 7
#
# Let's calculate the total area:
area = areaOfRect(5, 3) + areaOfRect(2, 8) + areaOfCircle(5) + areaOfCircle(7)
print("The total area is", area)
# We can also insert a function call directly into a string:
print("A circle with radius 10 has an area of", areaOfCircle(10))
Your Task
Create a file in your Unit-3 folder called a9.py.
Write a program similar to the example above, but choose different formulas. Be sure to pick descriptive function names to reflect what they calculate. Specifically, your program should:
- Define two functions
- Do a calculation that involves calling each function twice, each time with a different set of parameters
- Insert a call to one of your functions into a
printstatement