Python Functions

Python functions are reusable blocks of code that perform a specific task and can be called multiple times within a program to execute that task.

In Python, a function is a block of reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.

Defining a function

A function in Python is defined by a def statement. The general syntax looks like this:

def function_name(parameters):
    # function body
    return result  # this is optional

Let’s break down the components:

  • def: This keyword signals the start of a function definition.
  • function_name: This is the name of the function. It should be descriptive of what the function does and should follow the same naming conventions as variables.
  • parameters: These are inputs to the function. They are optional, and a function may contain zero or more parameters.
  • function body: This is where you write the code that the function should execute.
  • return: This keyword is used to exit the function and return a value. If no return statement is included, the function will return None by default.

Simple function example

Here is an example of a function that takes two numbers as inputs and returns their sum:

def add_numbers(a, b):
    return a + b

print(add_numbers(3, 5))  # Output: 8

In this example, add_numbers is the function name, a and b are parameters, and a + b is the function body. The function adds a and b together and returns the result.

More complex function example

Now, let’s consider a more complex example. Suppose we want to create a function that checks whether a number is prime (a number is considered prime if it is greater than 1 and has no divisors other than 1 and itself). Here’s how we could do it:

def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, n):
        if n % i == 0:
            return False
    return True

print(is_prime(2))  # Output: True
print(is_prime(4))  # Output: False

In this function, is_prime, we’re using a loop and conditional statements within our function body to check for the condition of being a prime number.

User-defined Functions

An example function

# Defines a "repeat" function that takes 2 arguments.
def repeat(s, exclaim):
    """
    Returns the string 's' repeated 3 times.
    If exclaim is true, add exclamation marks.
    """

    result = s + s + s # can also use "s * 3"
    if exclaim:
        result = result + '!!!'
    return result
  • The line indentation is the same for each statement
  • Using * rather than + is faster as the value is calculated once rather than being processed for each +
  • The def defines a function named repeat that takes two parameters, s and exclaim
  • s is a string and is the value that will be repeated
  • exclaim is a boolean that determines if an ! is added or not
  • The number of times the string is repeated is determined by the value of exclaim.

The result of running this code

repeated_str1 = repeat("hello", True)
print(repeated_str1)  # Output: "hellohellohello!!!"

repeated_str2 = repeat("world", False)
print(repeated_str2)  # Output: "worldworldworld"
Last modified July 21, 2024: update (e2ae86c)