Functions and Modules in Python

Functions bundle code and make programs maintainable. A module is a Python file with functions, classes and constants that you can reuse in other programs.

Defining functions

Use def to define a function. Parameters can have default values, return sends a result back:

def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

print(greet("World"))   # Hello, World!

Parameter types

  • Positional: order matters.
  • Keyword arguments: greet(name="World").
  • *args / **kwargs: arbitrary positional / keyword arguments.

Importing modules

import math, from datetime import datetime or import numpy as np. Your own modules are .py files imported by name.

Tips

  • Keep functions small (one job per function).
  • Use descriptive names instead of a, b.
  • if __name__ == "__main__": protects executable code from running on import.

See also: Python for Beginners.