Introduction

A function is a reusable block of code that performs a specific task. In Python, functions are defined using the def keyword. They help organize code, avoid repetition, and make programs more readable.

Syntax

def function_name(parameters):
    # code block
    return value
  • function_name is the name of the function (use lowercase and underscores)
  • parameters are inputs to the function (optional)
  • The return statement outputs a value (optional)

Examples

  1. Basic Function

    def greet():
        return "Hello, World!"
    
    python_function_syntax
  2. Function with Parameters

    def add(a, b):
        return a + b
    
    function_parameters
  3. Return Statement

    def multiply(x, y):
        result = x * y
        return result
    
    return_statement

Best Practices

  • Use descriptive names (e.g., calculate_area instead of ca)
  • Add docstrings to explain purpose:
    def square(n):
        """Return the square of a number."""
        return n ** 2
    
  • Avoid using return multiple times in a single function

Further Reading

For more about Python control flow, visit our Python Control Flow Tutorial.

python_control_flow