Python Crash Course
)}

Functions

So far, you learned how to:

  1. Code different data types and operators in Python
  2. Control how your code is executed using if-elif-else statements 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.

  1. The function declaration is always preceded with the keyword def
  2. It is good practice to name your functions using "snake_case" (lower case words separated by underscore)
  3. In parentheses, the function specifies arguments that must be passed into it.
  4. 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: length and 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.

print(rectangle_area(2, 3))

>>6

Using the 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))

>>6

>>24

>>27

>>6

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!

Feedback Summary
4.8
8 students
5

75%
4

25%
3

0%
2

0%
1

0%
Written Reviews
There are no written reviews yet.