Python Basics

Functions in Python: A Quick Guide

Table of Contents

Python functions are blocks of reusable code that perform a specific task. They help to make your code more modular, readable and maintainable. In this article, we will explore the basics of defining and using functions in Python.

Defining Functions

To define a function in Python, use the keyword def followed by the function name, brackets () and a colon :. The code block that follows the colon is the body of the function. Here’s an example:


def greet(name):
    """This function will greet the person that is passed as an argument."""
    print("Hello, " + name)

In this example, we define a function named greet that takes one argument, name. The function prints a greeting message using the given name.

Function Arguments

Functions can take zero or more arguments. If a function does not take any arguments, you can still define it with empty parentheses:


def greet():
    """This function greets the user without a name."""
    print("Hello!")

You can also specify default values for function arguments. If an argument is not passed when the function is called, Python uses the default value:


def greet(name="John"):
    """This function greets the person passed as an argument or 'John' if no argument is provided."""
    print("Hello, " + name)

Function Calls

To call a function, you simply write the name of the function, followed by brackets containing all the arguments you need. To call a function, you simply write the function name followed by parentheses containing any required arguments:


greet("Alice")  # Output: Hello, Alice
greet()         # Output: Hello!

Return Values

Functions can also return values. To return a value from a function, use the return keyword followed by the value:


def add(x, y):
    """This function adds two numbers."""
    result = x + y
    return result

sum = add(3, 5)  # Output: sum = 8
print(sum)       # Output: 8

Function Scope

Variables defined inside a function have local scope. They are only accessible within the function where they are defined:


def greet(name):
    message = "Hello, " + name
    print(message)

greet("Alice")  # Output: Hello, Alice
print(message)   # NameError: name 'message' is not defined

Function Docstrings

You can add a docstring to a function to provide documentation. A docstring is a string that appears just after the function definition and before the first indentation level:


def greet(name):
    """This function greets the person passed as an argument."""
    print("Hello, " + name)

To top