Python Keyword Reference

A quick reference for Python keywords, functions, and objects. Find what you need to build powerful applications.


The `def` Keyword

The def keyword is used to create, or define, a function in Python. Functions are reusable blocks of code that perform a specific action.

Functions are central to writing clean, modular, and efficient Python code. They help break down large programs into smaller, manageable pieces.

Example

my_functions.py

# Function definition
def greet(name):
  """This function greets the person passed in as a parameter"""
  return "Hello, " + name + "!"

# Calling the function
print(greet("World")) # Output: Hello, World!

# Function with a default argument
def say_hello(name="User"):
  return "Hello, " + name

print(say_hello()) # Output: Hello, User
print(say_hello("Alice")) # Output: Hello, Alice

Syntax

Basic syntax for defining a function:

SyntaxDescription
def function_name(parameters):Defines a function with a name and optional parameters.
"""docstring"""An optional string to document the function's purpose.
# code blockThe indented block of code that runs when the function is called.
return [expression]Exits the function and optionally passes back a value.