Defining Functions and Arguments

beginner level · ~20 min · Module 6: Functions & Scope

Create custom functions using def, handle positional and keyword arguments, and work with return values.

Learning objectives

  • Define functions using the def keyword
  • Use positional, default, and keyword arguments
  • Understand variable scope (LEGB rule: Local, Enclosing, Global, Built-in)

Lesson material

Function Definition

Functions encapsulate logic into callable blocks.

Example code

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

print(greet("Alice"))
print(greet("Bob", greeting="Welcome"))

Practice exercise: Multiply Function

Define a function `multiply(a, b=2)` that returns the product of `a` and `b`. Print `multiply(5)` and `multiply(5, 4)`.

Test yourself with the Module 6: Functions & Scope quiz →

View the full Python curriculum →