Skip to content

Function

In one line

A function is a reusable block of code defined with def that takes inputs (parameters) and returns an output.

In simple words

A function is a named, reusable block of code. You define it with the def keyword, give it a name, and specify parameters in parentheses. The body is indented below the definition.

Functions let you avoid repeating code. Instead of writing the same logic multiple times, you write it once in a function and call it wherever needed. Functions also make code easier to test and debug by isolating behavior.

A function can take zero or more parameters, perform operations, and optionally return a value with return. If no return statement is executed, the function returns None.

Example

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

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

Functions are defined with def, can have default parameters, and return values with return.

Common confusions

  • Confused with: method

    The difference: A function is standalone. A method is a function defined inside a class and called on an instance (obj.method()). All methods are functions, but not all functions are methods.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary