Free preview

100 lessons

Python Done Right

Free preview

Python Done Right · 100 lessons

Learn Python from scratch - syntax through to OOP

No surprise gaps

Actually remember it

Skip what you know

One subscription. All learning paths included.

Our content is best on a larger screen

User-defined functions

Syntax and definition

Explanation

To define a function in Python, we use the def keyword followed by a function name, parentheses (), and a colon :. The indented block beneath forms the function body:

def function_name(parameters):
    # Function body (indented)
    return <value>

Writing this creates a function object associated with the name function_name - analogous to how x = 5 associates the integer 5 with x.

Breakdown of each component

Details

Practice questions

4 questions

Which of the following correctly describes the role of the def keyword in Python?

Select the correct answer:

+ 3 more questions

Writing basic functions

Example

Here is a function that calculates the area of a rectangle, returning 0 if either dimension is non-positive:

def calculate_rectangle_area(length, width):
    area = 0
    if length > 0 and width > 0:
        area = length * width
    return area

The function takes two parameters (length and width), validates that both are positive, then computes the area. If either is non-positive, area stays at 0.

We call the function by passing arguments in the parentheses. Because it has a return statement, we can capture the result:

my_area = calculate_rectangle_area(2, 4)
print(my_area)  # Output: 8

print(calculate_rectangle_area(-2, 4))  # Output: 0
Validating function inputs

Details

Practice questions

4 questions

Recall the formula for the area of a circle:

area=π×radius2\text{area} = \pi \times \text{radius}^2

In the Python Editor, define a function called circle_area which takes a single required parameter, radius and returns the area of the circle if r is positive, otherwise it returns 0.

Use the value of 3.14159 for π\pi.

Once you've written your function, run the code which sums the areas for several test circles. What is the total area to 2 decimal places?

Select the correct answer:

+ 3 more questions