Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Python

Mastering Python Functions: Definition, Calling, Indentation, Arguments & Return Values

Mastering Python Functions: Definition, Calling, Indentation, Arguments & Return Values

Functions are the building blocks of any Python application. They encapsulate reusable logic, keep code DRY, and make your programs easier to read, test, and maintain. In this guide we’ll walk through every step you need to write, call, and troubleshoot functions in Python 3—while also touching on the differences you’ll encounter in Python 2.

What is a Function in Python?

A Python function is a self‑contained block of code that executes when you invoke it. You can think of it as a miniature program that performs a single, well‑defined task and can be reused wherever needed. While Python ships with numerous built‑in functions (e.g., print(), input()), you are free to craft your own, giving your code the power to evolve and scale.

Defining and Calling a Function

Functions are declared with the def keyword, followed by the function name and a parenthesized parameter list. The body of the function begins with a colon and must be indented.

def greet():
    print("Hello, Python!")

# Call the function
greet()

Output: Hello, Python!

Why Indentation Matters

Python does not use braces or explicit begin/end statements. Instead, indentation defines scope. Every block of code—functions, loops, conditionals—must share a consistent indentation level.

  1. At least one level of indentation (typically four spaces) is required after a function definition.
  2. All statements within that function must use the same indentation.
  3. Mixing tabs and spaces, or varying indentation depth, triggers a IndentationError.

Example of a correct indentation:

def demo():
    print("Line 1")
    print("Line 2")

And a common mistake:

def demo():
print("Oops")

which raises: IndentationError: expected an indented block

Using Return Statements

The return keyword sends a value back to the caller. If a function reaches the end without encountering a return, it implicitly returns None.

def square(x):
    return x * x

print(square(4))  # 16

Without return:

def square(x):
    x * x

print(square(4))  # None

Additionally, printing the function object itself (e.g., print(square)) displays its memory address, which is rarely useful in application code.

Passing Arguments to Functions

Arguments supply the data a function needs to operate. Parameters are the placeholders defined in the function signature.

def multiply(x, y=1):
    return x * y

print(multiply(4))        # 4  (y defaults to 1)
print(multiply(4, 2))     # 8
print(multiply(y=3, x=2)) # 6  (keyword arguments allow reordering)

Variable‑Length Arguments (*args and **kwargs)

Sometimes you need a function that accepts an arbitrary number of arguments. Use *args for positional arguments and **kwargs for keyword arguments.

def summarize(*values, **options):
    total = sum(values)
    print(f"Total: {total}")
    if options.get("show_details"):
        print("Values:", values)

summarize(1, 2, 3, 4, 5, show_details=True)

Python 2 vs Python 3: Key Differences

Best Practices for Function Design

Full Example

# Example of a comprehensive Python 3 script

def greet():
    """Print a friendly greeting."""
    print("Hello, Python!")


def square(x: int) -> int:
    """Return the square of x."""
    return x * x


def multiply(x: int, y: int = 1) -> int:
    """Return the product of x and y, with y defaulting to 1."""
    return x * y

# Demonstration
if __name__ == "__main__":
    greet()
    print(square(4))          # 16
    print(multiply(4))        # 4
    print(multiply(4, 2))     # 8
    print(multiply(y=2, x=4)) # 8

For more detailed guidance, refer to the official Python documentation on function definitions.

Python

  1. Master Python Functions: Syntax, Types, and Practical Examples
  2. Mastering Python Function Arguments: Positional, Keyword, and Default Parameters
  3. Master Python Lambda Functions: Practical Examples & Best Practices
  4. Python abs() Function: Compute Absolute Values for Numbers & Complex Numbers
  5. Python round() Function Explained with Practical Examples
  6. Mastering Python's map() Function: Syntax, Examples, and Best Practices
  7. Mastering Python’s Yield: Generator vs Return – A Practical Guide
  8. SciPy in Python: A Comprehensive Tutorial on Libraries & Functions
  9. How to Return Multiple Values in Python: A Simple Guide
  10. Python Functions Explained: Building Reusable Code Modules