Preview

A lesson from Python Done Right

£29/month

£29/month£29/month or £249/year · 30-day money-back guarantee

Get full access

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 · unlocked with a subscription

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 · unlocked with a subscription

Memory is built by recalling, not by reading.

Every time you pull an answer from memory, the memory gets stronger. Reading doesn't do that. Nodeledge asks you questions on every step of every lesson, then asks again after days, weeks and months.

Get full access

£29/month or £249/year · 30-day money-back guarantee

See the learning path