How to Create a Function in Python | The School of Code

Settings

Appearance

Choose a typography theme that suits your style

Back to How-to Guides
Python

How to Create a Function in Python

Learn how to define and use functions in Python with parameters, return values, and default arguments.

PythonFunctionsBasics

Functions are reusable blocks of code that perform specific tasks. Here’s how to create them in Python.

Basic Function Definition

Use the def keyword to define a function:

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

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

Functions with Multiple Parameters

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

result = add(3, 5)
print(result)  # 8

Default Parameters

Provide default values for optional parameters:

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

print(greet("Alice"))              # "Hello, Alice!"
print(greet("Bob", "Hi"))          # "Hi, Bob!"

Keyword Arguments

Call functions with named arguments:

def describe_person(name, age, city):
    return f"{name} is {age} years old and lives in {city}"

# Using keyword arguments (order doesn't matter)
print(describe_person(age=25, city="Paris", name="Alice"))

*args and **kwargs

Accept variable numbers of arguments:

# *args for variable positional arguments
def sum_all(*numbers):
    return sum(numbers)

print(sum_all(1, 2, 3, 4))  # 10

# **kwargs for variable keyword arguments
def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="Alice", age=25, city="Paris")

Lambda Functions

Create small anonymous functions:

# Regular function
def square(x):
    return x ** 2

# Lambda equivalent
square = lambda x: x ** 2

print(square(5))  # 25

Summary

  • Use def to define functions
  • Use default parameters for optional arguments
  • Use *args and **kwargs for flexible argument handling
  • Use lambda for simple, one-line functions