So far, you learned how to:
- Code different data types and operators in Python
- Control how your code is executed using
if-elif-elsestatements and loops
The final step is for you to learn how to organize your code using functions.
The skeleton of a function in Python is as follows:
def function_name(arg1, arg2): //function body
In this article, you will define a function that calculates the area of any rectangle.
Dissecting the function
There are 4 components to a function.
- The function declaration is always preceded with the keyword
- It is good practice to name your functions using "snake_case" (lower case words separated by underscore)
- In parentheses, the function specifies arguments that must be passed into it.
- The function body is code that is executed when the function is called.
Calculating the area of a rectangle
The area of a rectangle is just length multiplied by width.
For this example, you will define a function named
rectangle_area that calculates the area of a rectangle.
def rectangle_area(length, width): area = length * width return area
This function accepts two arguments:
width. It multiplies the two arguments to get the
area and returns it. The
return statement ends the execution of the function call and "returns" the result.
Using the function, print the area of a rectangle with a
length of 2 and a
width of 3.
rectangle_area function, print the areas of rectangles with the following lengths and widths:
print(rectangle_area(3, 2)) print(rectangle_area(4, 6)) print(rectangle_area(3, 9)) print(rectangle_area(2, 3))
How easy was that? All you have to do is change the arguments and the function calculates the area for a new rectangle.
In this article, you saw first-hand how functions are re-usable sections of code that are used to accomplish a specific task. They help to avoid copying and pasting code, and can be re-used to your heart's content!