โ† Python Basics

Functions and Modules

~300 words ยท 2 min read

Functions and Modules in Python

Functions package reusable logic. Modules organize related functions and classes into files you can import anywhere.

Defining Functions

Use def to create a function. Parameters can have default values, which makes them optional when calling.

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

greet("Ada")           # Hello, Ada!
greet("Ada", "Hi")     # Hi, Ada!

*args and **kwargs

The *args syntax collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. Together they let a function accept flexible inputs.

def log(*args, **kwargs):
    print("args:", args)
    print("kwargs:", kwargs)

log(1, 2, level="warn")
# args: (1, 2)
# kwargs: {"level": "warn"}

Lambda Expressions

A lambda is a small anonymous function limited to a single expression. It is handy for short callbacks, but it cannot contain statements.

square = lambda x: x * x
nums = [1, 2, 3]
doubled = list(map(lambda x: x * 2, nums))  # [2, 4, 6]

Lambdas are limited to one expression and cannot hold statements like if blocks or assignments. When logic grows beyond a single line, define a real function with def โ€” it is far more readable and debuggable.

The Import System

Python modules are just .py files. The import statement finds the module, runs its top-level code once, and caches the result in sys.modules. Later imports reuse the cached object without re-running the file.

import math
from collections import defaultdict
from datetime import datetime as dt

The __main__ Guard

The idiom if __name__ == "__main__": runs code only when a file is executed directly, not when it is imported. This lets one module serve as both a library and a script.

def main():
    print("running")

if __name__ == "__main__":
    main()