Functions & Modules

Python - A Quick Start for existing Programers

3 min read

Published Sep 16 2025, updated Sep 30 2025


21
0
0
0

Python

Functions

Functions are defined using the def keyword and then the contents of the function are indented. Function names, like variables, should be lower case snake case:

def my_function():
    print("My function")

And then to call the function (needs to be under where it is defined):

my_function()

Any function that doesn't return a value, will actually return a None value. To return a value you use the return keyword:

def my_function():
    print("My function")
    return "My return value"

Zero or many parameters can be passed to a function:

def my_function(my_parameter1, my_parameter2):
    print("My function", my_parameter1, my_parameter2)
    return "My return value"

Optional parameters can be defined a default value, which means you can call them with a parameter or without and it takes the default:

def my_function(my_parameter1="Default value", my_parameter2=42):
    print("My function", my_parameter1, my_parameter2)
    return "My return value"

result = my_function("Custom value", 100)
result2 = my_function()

When calling a function, you can specify the parameter names so that they can be added in any order:

def introduce(name, age):
    print(f"My name is {name}, and I am {age} years old.")

introduce(age=25, name="Bob")

Multiple positional arguments. Allows a variable amount of positional based parameters for a function, providing the parameters as a tuple:

def add_all(*args):
    return sum(args)

print(add_all(1, 2))
print(add_all(1, 2, 3, 4, 5))

Multiple keyword arguments. Allows a variable amount of keyword based parameters for a fucntion, providing the parameters as a key value pair dictionary:

def show_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

show_info(name="Alice", age=25, job="Engineer")


Combining Normal Parameters, *args, and **kwargs:

def example(a, b, *args, c=10, **kwargs):
    print("a:", a)
    print("b:", b)
    print("args:", args)
    print("c:", c)
    print("kwargs:", kwargs)

example(1, 2, 3, 4, 5, c=20, x=100, y=200)

Results in:

a: 1
b: 2
args: (3, 4, 5)
c: 20
kwargs: {'x': 100, 'y': 200}

Argument Unpacking with * and **:

def greet(name, age):
    print(f"Hi, I'm {name}, {age} years old.")

# Using * to unpack a tuple
person = ("Alice", 30)
greet(*person)
# Hi, I'm Alice, 30 years old.

# Using ** to unpack a dict
person_info = {"name": "Bob", "age": 25}
greet(**person_info)
# Hi, I'm Bob, 25 years old.




Lambda functions

A lambda function is a small, anonymous function defined with the lambda keyword. They are useful for short, throwaway functions where using def would be overkill.


lambda arguments: expression

  • arguments → zero or more parameters.
  • expression → a single expression (no statements, no multiple lines).
  • Returns the value of the expression automatically (no return needed).

Limitations

  • Can only contain one expression (no statements like print, for, if as standalone).
  • Not a replacement for normal functions — use def for anything non-trivial.
  • Less readable if overused (can hurt clarity).


Examples:

# --- Basics ---
add = lambda x, y: x + y
print("add(2, 3):", add(2, 3))
# 5

# No arguments
hello = lambda: "Hello!"
print(hello())
# Hello!

square = lambda x=2: x * x
print("square():", square())
# 4
print("square(5):", square(5))
# 25

nested = lambda x: (lambda y: y**x)
print("nested power:", nested(2)(5))
# 25

# --- filter() with lambda ---
evens = list(filter(lambda n: n % 2 == 0, nums))
print("filter -> evens:", evens)
# [2, 4]

# --- sorted() with lambda ---
words = ["banana", "apple", "cherry"]
sorted_by_length = sorted(words, key=lambda w: len(w))
print("sorted by length:", sorted_by_length)
# ['apple', 'banana', 'cherry']




Function variable scopes

Local variables created in a function are only accessible in that function:

def my_func():
    # local variable
    x = 10
    print(x)

my_func()

print(x)
# ERROR: x not defined

Global variables are accessible inside a function to read, however if you try and assign a variable a value, it will create a new local variable of that name:

# global variable
x = 100

def show():
    # can read global variable but can't set
    print(x)

show()

Using the global keyword inside a function will use the global variable, rather than creating a new local variable:

x = 5

def change():
    global x
    x = 10

change()

print(x)
# outputs 10 as the global variable is updated in the function


In nested functions, variables in the outer function are enclosing scope. Use nonlocal to modify them rather than creating a new local variable in the inner function:

def outer():
    x = "outer"
    
    def inner():
        nonlocal x
        x = "inner"
    
    inner()
    print(x)

outer()





Modules

A module is a .py file that contains Python code (functions, classes, variables, etc.).


An example file with two functions, called my_utils.py:

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

Importing a whole module, single import statement and then access the functions using name.function :

import my_utils

print(my_utils.add(5, 3))
print(ma_utils.subtract(5, 3))

Importing specific functions or classes, as they are specifically named, you can call the function directly without the name. prefix:

from my_utils import add

print(add(5, 3))

Importing more than one specific function or classes by comma separating the names:

from my_utils import add, subtract

Importing with aliases, renaming the function or class when importing:

import my_utils as mu
from my_utils import add as addition

print(mu.subtract(10, 4))
print(addition(7, 2))

Importing everything from a module in to the namespace, risky as can cause naming conflicts:

from my_utils import *
print(add(1, 2))
© 2025 SimpleSteps.guide
AboutFAQPoliciesContact