Uncategorized

How to Call a Function in Python [With Examples]


If you are a beginner Python programmer, learning to use functions will help you write modular code. So let’s learn how to define and call functions in Python.

When you’re coding in Python, you’ll sometimes find yourself repeating the same logic at multiple sections within the program. Instead, you can define a function to wrap the logic.

This will make the code modular and reusable. Because once you define a function, you can call it as many times as you’d like—with different values for arguments.

In this tutorial, you’ll learn how to:

  • Define and call Python functions
  • Define functions that take in arguments 
  • Define functions that return a value or multiple values 
  • Handle common errors when calling Python functions

Let’s begin.

Defining and Calling Python Functions

Let’s start by learning how to use built-in Python functions as well as define your own.

How to Work with Built-In Python Functions

Python has a large suite of built-in functions. You can get more information on any function by calling help(func_name).

Now let’s look at two common built-in functions:

The len() function helps us get the length (the number of items) of an object such as a string, list, tuple, or other iterable.

# Using len() with a list
my_list = [10, 20, 30, 40, 50]
list_length = len(my_list)

print(f"The length of the list is: {list_length}")

This outputs:

# Output
The length of the list is: 5

The sorted() function sorts the elements of a given iterable in ascending order by default. You can apply it to various iterable types, including lists.

# Using sorted() with a list
numbers = [5, 2, 8, 1, 7]
sorted_numbers = sorted(numbers)

print(f"Original list: {numbers}")
print(f"Sorted list: {sorted_numbers}")

Here’s the output:

# Output
Original list: [5, 2, 8, 1, 7]
Sorted list: [1, 2, 5, 7, 8]

🔖 To sort a list in descending order, you can set the reverse parameter to True. Learn more about sorting Python lists.

How to Define Your Own Functions

In Python, you can define custom functions using the def keyword, followed by the function name and a set of parameters enclosed within parentheses:

def my_function(parameter1, parameter2, ...):
    # function body
    # do something on the parameters
    return result  # Optional: If the function returns a value.

Here’s a breakdown of the key components of functions in Python:

  • Function name: A descriptive name for the function, usually formatted in snake case.
  • Parameters: Variables that represent input values passed to the function. They are enclosed in parentheses and are optional. A function can take no parameters at all. Or it can take one or more parameters as needed.
  • Function body: The indented block of code under the function definition. It contains statements that define what the function does.
  • Return statement: If the function produces and returns a result, the return statement is used to send that result back to the calling code.

Now let’s write a simple greet_user() function:

def greet_user():
    print("Hello! Welcome!")

# Calling the function
greet_user()

When you call the function, it prints out a simple greeting like so:

# Output
Hello! Welcome!

Notice that this function takes in no arguments and does not return anything. All it does is print out a simple greeting: ‘Hello! Welcome!’.

Functions that Take in Arguments

Let’s modify the function definition a bit. We’ve added a name parameter so that we can have a personalized greeting:

def greet_user(name):
    print(f"Hello, {name}! Welcome!")

# Calling the function with a specific name
greet_user("Alice")

Notice that we now pass in the string “Alice” in the function call. And the function now outputs:

# Output
Hello, Alice! Welcome!

Functions that Return Values

The greet_user() function only prints out the greeting and does not return any value. Let’s now define functions that return values.

Return a Single Value from a Python Function

The calculate_total_bill() function that calculates the total bill amount based on the following parameters:

  • base_amount,
  • tip_percentage, and 
  • tax percentage.

The function definition is as shown:

def calculate_total_bill(base_amount, tip_percentage, tax_percentage):
    """Calculate total bill with tip and taxes."""
    # Calculate tips and taxes
    tip = base_amount * (tip_percentage / 100)
    taxes = base_amount * (tax_percentage / 100)

    # Calculate total bill
    total_bill = base_amount + tip + taxes

    return total_bill

Let’s call the function with values for the parameters:

base_amount = 100
tip_percentage = 10
tax_percentage = 18

total_bill = calculate_total_bill(base_amount, tip_percentage, tax_percentage)
print(f"Your total bill is: ${total_bill:.2f}")

🔖 In the above function call, we pass in the arguments as positional arguments; the arguments are assigned to the parameters in the order in which they appear in the function call.

You can also pass in arguments as keyword arguments by mentioning the parameter_name=value pairs in the function call. This can help improve readability.

I’m sure you also noticed the docstring enclosed within triple quotes (”’) in the function definition. These allow you to add descriptions of what the function does and serve as inline documentation.

Like built-in functions, when you can call the help() function with user-defined functions, users can see the docstring:

help(calculate_total_bill)

# Output
Help on function calculate_total_bill in module __main__:

calculate_total_bill(base_amount, tip_percentage, tax_percentage)
    Calculate total bill with tip and taxes.

Return Multiple Values from a Python Function

Now we modify the calculate_total_bill() function like so:

def calculate_total_bill(base_amount, tip_percentage, tax_percentage):
    """Calculate total bill with tip and taxes."""
    # Calculate tips and taxes
    tip = base_amount * (tip_percentage / 100)
    taxes = base_amount * (tax_percentage / 100)

    # Calculate total bill
    total_bill = base_amount + tip + taxes

    return total_bill, tip, taxes

In addition to the total bill amount, the function now also returns the taxes and the tip amount.

Here’s a sample function call:

base_amount = 100
tip_percentage = 10
tax_percentage = 18

total_bill, tip, taxes = calculate_total_bill(base_amount, tip_percentage, tax_percentage)
print(f"Your total bill is: ${total_bill:.2f}")
print(f"Tip amount: ${tip:.2f}")
print(f"Taxes: ${taxes:.2f}")

As seen, we get the total bill amount, tip amount, and taxes from the return values of the function:

# Output
Your total bill is: $128.00
Tip amount: $10.00
Taxes: $18.00

Handling Common Errors When Calling Python Functions

In the examples we’ve seen so far, the function calls work—without errors—and return the expected results.

However, there are some pitfalls you should be aware of when calling functions in Python. In this section, we’ll discuss the following using the calculate_total_bill() function as an example:

  • Invalid Input
  • Incorrect number of arguments
  • Unpacking errors

Here’s the calculate_total_bill() function for your reference:

def calculate_total_bill(base_amount, tip_percentage, tax_percentage):
    """Calculate total bill with tip and taxes."""
    # Calculate tips and taxes
    tip = base_amount * (tip_percentage / 100)
    taxes = base_amount * (tax_percentage / 100)

    # Calculate total bill
    total_bill = base_amount + tip + taxes

    return total_bill, tip, taxes

#1. Invalid Input Type

When calling functions, you should be careful to pass in arguments of the correct data type. The calculate_total_bill() function takes in three arguments—all of which should be valid numeric data types.

Here, we replace the second argument with the string ‘abc’ and call the function:

total, tips, taxes = calculate_total_bill(100, 'abc', 8)

You’ll run into a TypeError exception as shown:

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-9-31c2b1a4031c> in <cell line: 1>()
----> 1 total, tips, taxes = calculate_total_bill(100, 'abc', 8)

<ipython-input-7-1c7f56a4fe57> in calculate_total_bill(base_amount, tip_percentage, tax_percentage)
      2     """Calculate total bill with tip and taxes."""
      3     # Calculate tips and taxes
----> 4     tip = base_amount * (tip_percentage / 100)
      5     taxes = base_amount * (tax_percentage / 100)
      6 

TypeError: unsupported operand type(s) for /: 'str' and 'int'

You can also add type hints to add the expected data types for the different parameters.

#2. Incorrect Number of Arguments

In addition to the data type of arguments, you should also be careful to use the correct number of arguments in the function call.

Recall that we should have three arguments in the calculate_total_bill() function call. So what happens if you forget one of them?

total, tips, taxes = calculate_total_bill(100, 10)

You’ll get the following error as we’re missing one required positional argument in our function call:

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-14-1ca562728da1> in <cell line: 1>()
----> 1 total, tips, taxes = calculate_total_bill(100, 10)

TypeError: calculate_total_bill() missing 1 required positional argument: 'tax_percentage'

#3. Unpacking Errors

When working with functions that return multiple values, you may run into errors when unpacking the return values.

total, tips = calculate_total_bill(100, 10, 8)

Here, there are three return values but only two variables on the left-hand side of the assignment statement. So we get a ValueError as shown:

---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-15-4364e57a3faa> in <cell line: 1>()
----> 1 total, tips = calculate_total_bill(100, 10, 8)

ValueError: too many values to unpack (expected 2)

Wrapping Up

We’ve learned how to define and call functions in Python with a focus on the following:

  • Working with built-in and user-defined functions in Python 
  • Defining and calling functions that take in one or more arguments and return one or more values 
  • Handling common errors due to input argument type, number, and unpacking return values from functions

Next, learn how to round numbers in Python.



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *