Python Functions: Definitive Guide & Examples

Master Python functions. Learn how to write reusable code using def, define arguments, return values, and understand scope locally and globally.

Try Python Functions Code

Overview

A function is a block of organized, reusable code that is used to perform a single, related action.

Functions provide better modularity for your application and a high degree of code reusing. Python gives you many built-in functions like print(), but you can also create your own functions.

You define functions using the "def" keyword, followed by the function name and parentheses containing optional parameters.

Code Example

Here is a simple function that calculates the tax applied to a price, demonstrating parameters and return values.

functions_demo.py
Try in Editor
def calculate_total(price, tax_rate=0.08):
    """
    Calculates the final price after applying tax.
    """
    tax_amount = price * tax_rate
    total = price + tax_amount
    return total

print(calculate_total(100.00))
print(calculate_total(50.00, tax_rate=0.10))
Terminal Output
108.0
55.0

Real-world Use Cases

  • Encapsulating complex mathematical formulas
  • Separating UI logic from backend business logic
  • Creating utility modules for team collaboration

Frequently Asked Questions

What are default arguments?

Default arguments are values that are used if no argument is provided during the function call.

Can a function return multiple values?

Yes, Python allows functions to return multiple values by separating them with commas. Under the hood, this returns a tuple.

Keep Learning