Back to course

Introduction to Functions: Defining and Calling

Python Programming: The 0 to Hero Bootcamp

Functions: Reusable Code Blocks

A function is a named sequence of statements that performs a computation. Functions are crucial for making code modular, reusable, and easy to maintain.

Defining a Function

Use the def keyword, followed by the function name, parentheses (), and a colon :. The function body must be indented.

python def greet(): """This function prints a simple greeting.""" print("Hello from the function!")

Calling a Function

To execute the code inside the function, you must call it by its name followed by parentheses.

python greet() # Executes the function block

Output: Hello from the function!

Docstrings (Documentation Strings)

Immediately after the function header, you should include a docstring (using triple quotes). This documents what the function does, and is accessible via the help() function or an IDE.

python help(greet)

Output: This function prints a simple greeting.