← Back to Python Course | Chapter 4: Functions | Lesson 1 of 9

Python Functions Introduction

What is a Function?

A function is a named, reusable block of code defined with the def keyword that only runs when explicitly called — bundling logic into a function means writing it once and invoking it as many times as needed instead of repeating code.

Example: What is a Function?

python
def greet():
    print("Hello!")

greet()
greet()

Calling a Function

Writing def greet(): only registers the function's definition with the interpreter; nothing inside its body actually executes until you separately write greet() with parentheses to call it.

Example: Calling a Function

python
def greet():
    print("Hi there")

# Nothing runs until greet() is called
greet()

docstrings

A docstring is a string literal placed as the very first line inside a function's body, documenting what the function does; tools like help() and most IDEs display it automatically, making it far more useful than an ordinary comment.

Example: docstrings

python
def greet():
    """Prints a friendly greeting."""
    print("Hello!")

print(greet.__doc__)

Control Flow in Functions

A function body can contain the full range of Python constructs — conditionals, loops, and calls to other functions — meaning functions can be as simple as one line or coordinate substantial logic internally.

Example: Control Flow in Functions

python
def classify(n):
    if n % 2 == 0:
        return "even"
    else:
        return "odd"

print(classify(4))

Dynamic Execution of Functions

Because functions are first-class objects in Python, you can assign one to a variable, store several in a list, or pass one as an argument to another function — treating behavior itself as a value you can move around, not just data.

Example: Dynamic Execution of Functions

python
def greet():
    print("Hello!")

say_hi = greet
say_hi()

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.