Skip to main content
  • Python is available now. All other compilers are coming soon.

    Python
  • Popular Tutorials

    • Getting Started With Python
    • Python if Statement
    • while Loop in Python
    • Python Lists
    • Dictionaries in Python
    All Python Tutorials

    Reference Materials

    Built-in FunctionsList MethodsDictionary MethodsString Methods
    View all

Online Compilers

  • Python Compiler
  • Python Playground
  • Python Projects
  • Exercises

Tutorials

  • Learn Python
  • Python for Beginners
  • Variables and Types
  • Python Strings
  • Python Lists
  • Python If Else
  • Python For Loops
  • Python Functions
  • Python Classes

Examples

  • Python Examples
  • Hello World
  • Add Two Numbers
  • Even or Odd
  • Factorial
  • Fibonacci
  • Prime Check
  • Palindrome Check

Company

  • About
  • Contact
  • Privacy Policy
  • Terms of Use
  • Disclaimer

© 2026 ILoveCompiler. All rights reserved.

  1. Home
  2. Python Tutorial
  3. Python Functions: Define, Call, and Return Values

Functions · Tutorial 19

Python Functions: Define, Call, and Return Values

Write reusable code with def, pass arguments, return results, and use docstrings to document behaviour.

Open the compilerPractice exercises
beginner9 min readUpdated November 19, 20264 learning goals
On this page
  1. Calling a function
  2. Returning early
  3. Functions without a return
  4. Docstrings
  5. Type hints
  6. Small functions
  7. Functions calling functions
  8. Practice

What you will learn

  • Define and call functions
  • Pass arguments and return values
  • Use docstrings and type hints
  • Understand why functions improve programs
Before this lesson: Python Lists: Creation, Indexing, and Iteration, Python Dictionaries: Keys, Values, and Practical Patterns

A function packages a block of code under a name so it can be reused. Define one with def.

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


result = greet("Ada")
print(result)
Expected output

Hello, Ada!

The function has:

  • A name: greet.
  • A parameter: name.
  • A body: the indented lines.
  • A return value: the expression after return.

Calling a function#

Calling means using the function name followed by parentheses:

Python
print(greet("Grace"))

Arguments are matched to parameters in order. The returned value replaces the call expression, so greet("Grace") becomes the string it returns.

Returning early#

return exits the function immediately:

Python
def absolute(value):
    if value < 0:
        return -value
    return value


print(absolute(-7))  # 7

Code after a return in the same block is unreachable. Keep branches simple so every path is obvious.

Functions without a return#

If no return runs, the function returns None:

Python
def show_total(items):
    print(f"Total items: {len(items)}")


result = show_total([1, 2, 3])
print(result)
Expected output

Total items: 3 None

Prefer returning a value and letting the caller decide how to display it. Pure functions are easier to test and reuse.

Docstrings#

The first statement in a function can be a string that documents it:

Python
def rectangle_area(width, height):
    """Return the area of a rectangle.

    Both dimensions are expected to be non-negative numbers.
    """
    return width * height

help(rectangle_area) displays the docstring. The description should explain behaviour, assumptions, and the meaning of parameters, not restate the code.

Type hints#

Optional annotations document expected types and support editors:

Python
def average(numbers: list[float]) -> float:
    return sum(numbers) / len(numbers)

Python does not enforce annotations at runtime. They are documentation and tooling support, not validation. Use mypy or pyright for static checking.

Small functions#

Good functions have one clear job. Compare:

Python
def process(values):
    cleaned = [value.strip().lower() for value in values if value.strip()]
    return sorted(set(cleaned))

with a function that reads input, cleans data, computes statistics, prints a report, and writes a file. The first is easier to test and change.

Name functions with verbs

Use names such as calculate_total, is_valid, load_settings, or format_price. A function that returns a boolean often reads best with is_ or has_.

Functions calling functions#

Python
def is_even(number):
    return number % 2 == 0


def count_evens(numbers):
    return sum(1 for number in numbers if is_even(number))


print(count_evens([1, 2, 4, 7, 10]))
Expected output

3

Composing small functions keeps each piece readable and independently testable.

Practice#

Write three functions: is_prime(n), count_primes(limit), and print_primes(limit). The first returns a boolean, the second returns an integer, and the third prints the values. Notice how count_primes can reuse is_prime without duplicating logic.

Previous tutorialPython Sets: Unique Values and Set OperationsNext tutorialPython Function Arguments: Defaults, Keyword, and *args

Related tutorials

intermediate

Python Function Arguments: Defaults, Keyword, and *args

Use positional and keyword arguments, default values, *args, **kwargs, and avoid mutable default pitfalls.

9 min read
intermediate

Python Variable Scope and Object Lifetime

Understand local, global, and nonlocal scope, when variables are created, and why modifying globals inside functions is risky.

8 min read

On this page

  1. Calling a function
  2. Returning early
  3. Functions without a return
  4. Docstrings
  5. Type hints
  6. Small functions
  7. Functions calling functions
  8. Practice

Run the examples

Every Python block has a Run in compiler button that opens the code in a new tab.