How to Define a Function in Python?

In this tutorial, I will explain how to define a function in Python. In one of my projects for my clients, I came across a scenario where I needed to define a function. Functions are a fundamental concept in programming that allows you to organize and reuse code. Let us learn more about defining functions with examples and screenshots.

Python Functions

Before getting into the details of defining a function, let’s understand the basic concepts. A function is a block of code that only runs when it is called. You can pass data, known as parameters, into a function, and it can return data as a result.

Read How to Get the Name of a Function in Python?

Define a Function in Python

To define a function in Python, you use the def keyword followed by the function name and parentheses. Inside the parentheses, you can specify parameters that the function can accept. After the parentheses, add a colon and start a new indented block for the function body.

Here’s the general syntax for defining a function:

def function_name(parameter1, parameter2, ...):
    # Function body
    # Perform some operations
    return result

Let’s break it down:

  • def is the keyword used to define a function.
  • function_name is the name you give to your function. Choose a descriptive name that reflects the purpose of the function.
  • parameter1, parameter2, etc., are optional parameters that the function can accept. These are placeholders for values that you can pass to the function when calling it.
  • The function body is indented and contains the code that will be executed when the function is called.
  • The return statement is used to specify the value that the function should return. It is optional, and if omitted, the function will return None.

Check out How to Use the Input() Function in Python?

Example: Calculate the Area of a Rectangle

Let’s create a function that calculates the area of a rectangle given its length and width. We’ll call the function calculate_rectangle_area and define it as follows:

def calculate_rectangle_area(length, width):
    area = length * width
    return area

In this example:

  • The function name is calculate_rectangle_area.
  • It accepts two parameters: length and width.
  • The function body calculates the area by multiplying length and width.
  • The calculated area is returned using the return statement.

Check out How to Use Default Function Arguments in Python?

Call a Function

Once you have defined a function, you can call it by using its name followed by parentheses and passing any required arguments. To call a function, simply write the function name followed by parentheses containing the arguments (if any).

Let’s call our calculate_rectangle_area function:

length = 5
width = 3
area = calculate_rectangle_area(length, width)
print(f"The area of a rectangle with length {length} and width {width} is {area}.")

Output:

The area of a rectangle with length 5 and width 3 is 15.

You can see the output in the screenshot below.

Define a Function in Python

In this example, we assign the values 5 and 3 to the variables length and width, respectively. We then call the calculate_rectangle_area function, passing length and width as arguments. The function returns the calculated area, which we store in the area variable and print the result.

Read How to Exit a Function in Python?

Function Parameters and Arguments

Functions can accept parameters, which are values passed to the function when it is called. Parameters are like placeholders for the actual values (arguments) that will be provided when calling the function.

Positional Arguments

Positional arguments are passed to a function based on their position or order. The values provided must match the number and order of the parameters defined in the function.

Let’s modify our previous example to include a default value for the width parameter:

def calculate_rectangle_area(length, width=2):
    area = length * width
    return area

Now, if we call the function with only one argument, it will use the default value of 2 for the width:

area1 = calculate_rectangle_area(5)
print(f"Area with default width: {area1}")

area2 = calculate_rectangle_area(5, 3)
print(f"Area with provided width: {area2}")

Output:

Area with default width: 10
Area with provided width: 15

You can see the output in the screenshot below.

How to Define a Function in Python

Check out How to Call a Function Within a Function in Python?

Keyword Arguments

Keyword arguments allow you to pass values to a function using the parameter names. This way, you can provide arguments in any order, as long as you specify the parameter names.

area = calculate_rectangle_area(width=3, length=5)
print(f"Area with keyword arguments: {area}")

Output:

Area with keyword arguments: 15

You can see the output in the screenshot below.

Define a Function in Python Keyword Arguments

Check out How to Use Static Variables in Python Functions?

Return Values from a Function

Functions can return values using the return statement. The returned value can be assigned to a variable or used directly in an expression.

Let’s create a function that checks if a given number is even:

def is_even(number):
    if number % 2 == 0:
        return True
    else:
        return False

We can call this function and use the returned value in a conditional statement:

num = 7
if is_even(num):
    print(f"{num} is even.")
else:
    print(f"{num} is odd.")

Output:

7 is odd.

Read How to Use Python Functions with Optional Arguments?

Example: Calculate Sales Tax

Let’s consider a real-world scenario where we need to calculate the sales tax for a purchase in the United States. Different states have different tax rates, so we’ll create a function that takes the purchase amount and state as parameters and returns the total amount including tax.

def calculate_total_with_tax(amount, state):
    tax_rates = {
        "CA": 0.0725,
        "NY": 0.04,
        "TX": 0.0625,
        "FL": 0.06
    }

    if state in tax_rates:
        tax_rate = tax_rates[state]
        tax = amount * tax_rate
        total = amount + tax
        return total
    else:
        return amount

In this function:

  • We define a dictionary tax_rates that maps state abbreviations to their respective tax rates.
  • We check if the provided state is in the tax_rates dictionary.
  • If the state is found, we calculate the tax by multiplying the amount by the corresponding tax rate.
  • We add the tax to the original amount to get the total.
  • If the state is not found, we return the original amount without applying any tax.

Let’s use this function to calculate the total amount for a purchase:

purchase_amount = 100
state = "CA"
total = calculate_total_with_tax(purchase_amount, state)
print(f"Purchase amount: ${purchase_amount:.2f}")
print(f"State: {state}")
print(f"Total with tax: ${total:.2f}")

Output:

Purchase amount: $100.00
State: CA
Total with tax: $107.25

Check out How to Use Lambda Functions in Python?

Conclusion

In this tutorial, I helped you learn how to define a function in Python. I discussed defining and calling a function in Python with an example, and position and keyword arguments. I also discussed returning values from functions with examples to calculate sales tax.

You may read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.