Home / Topic Library / Python / Functions
🐍 Python Topic Library

Python Functions — def, Arguments, Return & Scope

Functions turn repeated code into named, reusable tools. They're the single biggest step from "writing lines" to "building programs" — and Python's argument system is richer than most beginners realise.

⚡ Quick Answer

Define with def name(params):, hand results back with return. Call it with name(args). Parameters can have defaults (def greet(name="Guest")), and callers can name them: greet(name="Ada").

§Defining & calling

basics.py
def greet(name):
    """Say hello politely."""      # docstring — describe it!
    return f"Hello, {name}!"

message = greet("Ada")     # call it — returns a value
print(message)             # Hello, Ada!
print(greet("Alan"))       # call again — that's the point!

§Return vs print — the big one

print shows a value on screen; return hands it back to the caller so the program can use it. Functions without return give back None.

return_vs_print.py
def add_print(a, b):
    print(a + b)          # shows 7, returns None

def add_return(a, b):
    return a + b          # hands 7 back

x = add_print(3, 4)       # prints 7
print(x)                  # None — nothing was returned!
y = add_return(3, 4)
print(y * 10)             # 70 — usable result

§Default & keyword arguments

defaults.py
def power(base, exponent=2):     # default value
    return base ** exponent

print(power(5))              # 25 — uses default
print(power(5, 3))           # 125 — positional
print(power(exponent=3, base=2))   # 8 — named, any order

§*args and **kwargs

Accept any number of arguments — the pattern behind flexible APIs like print().

args_kwargs.py
def summarize(*nums, **options):
    total = sum(nums)
    if options.get("average"):
        return total / len(nums)
    return total

print(summarize(1, 2, 3))                  # 6
print(summarize(1, 2, 3, average=True))    # 2.0

§Scope — where names live

scope.py
counter = 0            # global

def bump():
    local = 5          # exists only inside bump
    return counter + local   # reading globals: fine

print(bump())          # 5
# print(local)         # NameError — local is gone outside

§Lambdas — tiny anonymous functions

lambdas.py
double = lambda x: x * 2
print(double(8))                    # 16

# their real home: as arguments
words = ["bb", "a", "ccc"]
words.sort(key=lambda w: len(w))
print(words)                        # ['a', 'bb', 'ccc']

§Common Mistakes to Avoid

🚨 Watch out for these
  • Confusing print with return — a function that only prints can't feed its result into other code — return the value, print at the call site
  • Mutable default argumentsdef f(items=[]) shares ONE list across all calls — use items=None then items = items or []
  • Forgetting the parenthesesgreet is the function object; greet() actually calls it

§Frequently Asked Questions

What's the difference between a parameter and an argument?

Parameters are the names in the def line; arguments are the actual values you pass when calling. def greet(name) — name is the parameter, "Ada" is the argument.

What does a function return if there's no return statement?

None. Any function without an explicit return (or with a bare return) hands back None.

What are *args and **kwargs?

*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict — letting functions accept flexible inputs.

When should I use a lambda?

Only for tiny throwaway functions passed as arguments, like sort keys. If it needs a name or more than one expression, use def.

🎓 Want to master Python properly?This reference covers one topic — the full free course takes you from zero to projects, with quizzes and a certificate.
Start the Free Python Course →

§Related Python Topics

← LoopsClasses & OOP →