Skip to main content
All tracks
Python Basics

Functions in Python

A function is a reusable block of code defined with def.

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

print(greet("PrepVerse")) # Hello, PrepVerse!
print(greet("PrepVerse", "Welcome")) # Welcome, PrepVerse!

Arguments​

def total(*numbers, **options):
s = sum(numbers)
return s * options.get("factor", 1)

print(total(1, 2, 3, factor=2)) # 12
  • *args collects extra positional arguments into a tuple.
  • **kwargs collects extra keyword arguments into a dict.

Lambda functions​

square = lambda x: x * x
print(sorted([3, 1, 2], key=lambda v: -v)) # [3, 2, 1]

Scope​

Variables assigned inside a function are local. Use global or nonlocal only when you really need to rebind an outer name.

CAUTION

Avoid mutable default arguments such as def f(items=[]). The same list is reused across calls. Use None and create the list inside the function.

Finished reading?

Mark it complete to track your progress across the docs.

Questions and discussion

Stuck on something here, or found a clearer way to explain it? Start a thread.

All discussions
  • Ask a question or share what helped
  • React to useful answers
  • Sign in with GitHub to post

Comments are stored in GitHub Discussions and shown here by giscus. PrepVerse never sees your GitHub password.