Difference Between Functions and Methods in Python

In this tutorial, I will explain the difference between functions and methods in Python. One of my team members asked me some doubt regarding the difference between functions and methods, I explored more about this topic and I will share my findings in this article with examples and screenshots of executed example code.

Function in Python

A function in Python is a standalone block of code that is designed to perform a specific task. It can take inputs, known as parameters, and can also return outputs. Functions are defined using the def keyword followed by the function name and parentheses.

Read How to Create an Empty Tuple in Python?

Characteristics of Functions

  • Independence: Functions are not tied to any object or class.
  • Modularity: Functions promote code reuse and modularity.
  • Flexibility: They can be called from anywhere in the code.

Example of a Function

Here’s a simple example of a function that calculates the sales tax for a given amount in Texas:

def calculate_sales_tax(amount, tax_rate=0.0825):
    """
    Calculate the sales tax for a given amount in Texas.
    :param amount: The amount on which tax is to be calculated.
    :param tax_rate: The tax rate (default is 8.25% for Texas).
    :return: The calculated tax.
    """
    return amount * tax_rate

# Calling the function
total_tax = calculate_sales_tax(100)
print(f"The sales tax for $100 in Texas is ${total_tax:.2f}")

Output:

The sales tax for $100 in Texas is $8.25

I have executed the above example code and added the screenshot below.

Functions and Methods in Python

In this example, calculate_sales_tax is a function that takes an amount and an optional tax rate, and returns the calculated tax.

Check out How to Access Tuple Elements in Python?

Method in Python

A method in Python is similar to a function but is associated with an object. Methods are defined within the context of a class and operate on instances of that class. They can modify the object’s state or perform operations using the object’s attributes.

Characteristics of Methods

  • Association with Objects: Methods belong to objects or classes.
  • Encapsulation: Methods encapsulate behavior specific to an object.
  • Dependency: Methods often rely on the state of the object they belong to.

Check out How to Print a Tuple in Python?

Example of a Method

Here’s an example of a method within a ShoppingCart class that adds an item to the cart:

class ShoppingCart:
    def __init__(self):
        self.items = []

    def add_item(self, item, price):
        """
        Add an item to the shopping cart.
        :param item: Name of the item.
        :param price: Price of the item.
        """
        self.items.append({'item': item, 'price': price})

    def total_price(self):
        """
        Calculate the total price of items in the cart.
        :return: The total price.
        """
        return sum(item['price'] for item in self.items)

# Creating an instance of ShoppingCart
cart = ShoppingCart()
cart.add_item('Laptop', 999.99)
cart.add_item('Headphones', 199.99)

print(f"Total price of items in the cart: ${cart.total_price():.2f}")

Output:

Total price of items in the cart: $1199.98

I have executed the above example code and added the screenshot below.

Difference Between Functions and Methods in Python

In this example, add_item and total_price are methods that operate on instances of the ShoppingCart class.

Read How to Check if a Tuple is Empty in Python?

Key Differences Between Functions and Methods in Python

Understanding the differences between functions and methods is essential for effective Python programming. Here are the key distinctions:

FeatureFunctionsMethods
DefinitionDefined using def keywordDefined within a class
AssociationStandalone, not associated with any objectAssociated with an object or class
InvocationCalled directly by nameCalled on an object using dot notation
ScopeOperates independentlyOperates on the object’s state
EncapsulationDoes not encapsulate object-specific behaviorEncapsulates behavior specific to an object
Examplecalculate_sales_tax(amount)cart.add_item('Laptop', 999.99)

Check out How to Convert Tuple to Int in Python?

Examples

Let us understand in a better way with the help of examples.

Example 1: Use Functions

Let’s consider a scenario where we need to calculate the average temperature for a week in New York. We can create a function to handle this calculation:

def average_temperature(temperatures):
    """
    Calculate the average temperature from a list of temperatures.
    :param temperatures: List of daily temperatures.
    :return: The average temperature.
    """
    return sum(temperatures) / len(temperatures)

# List of temperatures in New York for a week
ny_temperatures = [55, 60, 58, 62, 59, 61, 57]

# Calling the function
avg_temp = average_temperature(ny_temperatures)
print(f"The average temperature in New York for the week is {avg_temp:.2f}°F")

Example 2: Use Methods

Now, let’s create a WeatherStation class that includes methods for recording and analyzing temperatures:

class WeatherStation:
    def __init__(self, location):
        self.location = location
        self.temperatures = []

    def record_temperature(self, temperature):
        """
        Record a new temperature.
        :param temperature: The temperature to record.
        """
        self.temperatures.append(temperature)

    def average_temperature(self):
        """
        Calculate the average temperature.
        :return: The average temperature.
        """
        return sum(self.temperatures) / len(self.temperatures) if self.temperatures else 0

# Creating an instance of WeatherStation for New York
ny_station = WeatherStation("New York")

# Recording temperatures
ny_station.record_temperature(55)
ny_station.record_temperature(60)
ny_station.record_temperature(58)
ny_station.record_temperature(62)
ny_station.record_temperature(59)
ny_station.record_temperature(61)
ny_station.record_temperature(57)

# Calculating the average temperature
avg_temp = ny_station.average_temperature()
print(f"The average temperature recorded by the New York station is {avg_temp:.2f}°F")

In this example, record_temperature and average_temperature are methods that operate on the WeatherStation object.

Check out Python Dictionary Count

Conclusion

In this tutorial, I helped you to learn the difference between functions and methods in Python. I explained what are functions and methods in Python with characteristics and examples. I also covered the key differences between functions and methods in Python and some examples to illustrate the usage of functions and methods.

You may also like to 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.