Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to create a function in Python

Introduction to Functions in Python

If you're learning programming, you might have heard of the term "function" and how they are an essential building block in most programming languages. In this blog post, we will be discussing what functions are, why they are useful, and how to create and use them in Python. We'll present examples that you can follow along, to help you understand the concepts better.

What is a Function?

A function is a block of reusable code that performs a specific task. Functions make your code more organized, modular, and easier to understand. Think of a function like a recipe in a cookbook. A recipe contains ingredients (inputs), a set of instructions (code), and the final dish that it produces (output). Similarly, a function takes in some inputs (called arguments), processes the inputs according to the code inside the function, and returns a result (output).

Why are Functions Useful?

Reusability: Functions allow you to write code once and reuse it multiple times in different parts of your program. This helps reduce redundancy and makes your code more efficient.

Abstraction: Functions help you break down complex problems into smaller, manageable pieces. This makes your code more readable and easier to understand.

Ease of maintenance: By encapsulating related code in functions, it becomes easier to update or modify the code in the future. You can change the implementation of a function without affecting the rest of your program, as long as the function's inputs and outputs remain the same.

Creating a Function in Python

In Python, you can create a function using the def keyword, followed by the function name, a pair of parentheses containing the input parameters (if any), and a colon. The function's code block is then indented, typically by four spaces or a tab.

Here's an example of a simple function that takes no input arguments and prints "Hello, World!" when called:

def greet():
    print("Hello, World!")

greet()  # Calling the function

When we run this code, the output will be:

Hello, World!

Let's break down this example:

  • def greet(): defines a new function named greet. The empty parentheses indicate that this function does not take any input arguments.
  • The indented block of code below the function definition is the function's body. In this case, the body consists of a single line of code: print("Hello, World!").
  • To call (or use) the function, simply write the function's name followed by parentheses, like this: greet().

Function Arguments

In the previous example, our function did not take any input arguments. However, most functions require some input to perform their tasks. You can specify input arguments by adding variable names inside the parentheses when defining the function. When calling the function, you need to provide values for these input arguments.

Here's an example of a function that takes two input arguments and returns their sum:

def add(a, b):
    result = a + b
    return result

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

In this example, a and b are the input arguments of the function add. The function adds the values of a and b and stores the result in a variable named result. The return statement then returns the value of result to the caller.

When we call the function with add(5, 3), the values 5 and 3 are passed as arguments for a and b, respectively. The function returns the sum of these values (8), which is stored in the variable sum_result. Finally, we print the value of sum_result to display the output.

Returning Multiple Values

A function can return multiple values by separating them with commas in the return statement. When calling such a function, you can use multiple variables to store the returned values.

Here's an example of a function that takes two input arguments and returns both their sum and product:

def add_and_multiply(a, b):
    sum_result = a + b
    product_result = a * b
    return sum_result, product_result

add_result, multiply_result = add_and_multiply(5, 3)
print(add_result)  # Output: 8
print(multiply_result)  # Output: 15

In this example, the function add_and_multiply returns two values: the sum and product of the input arguments. When calling the function, we use two variables (add_result and multiply_result) to store the returned values. We then print these values to display the output.

Default Argument Values

Sometimes, you might want to have default values for some of the input arguments of a function. You can do this by assigning a default value to the argument in the function definition using the assignment operator =.

Here's an example of a function that takes two input arguments, but the second argument has a default value of 1:

def power(base, exponent=1):
    return base ** exponent

result_1 = power(2)  # Calling the function with one argument
print(result_1)  # Output: 2

result_2 = power(2, 3)  # Calling the function with two arguments
print(result_2)  # Output: 8

In this example, the function power takes two input arguments, base and exponent. However, we have assigned a default value of 1 to the exponent argument. This means that if we call the function with only one argument, the exponent will have the default value of 1.

When we call the function with power(2), the base argument is set to 2, and the exponent argument takes its default value of 1. The function returns the result of 2 ** 1, which is 2.

When we call the function with power(2, 3), both the base and exponent arguments are provided values (2 and 3, respectively). The function returns the result of 2 ** 3, which is 8.

Conclusion

In this blog post, we covered the basics of creating and using functions in Python. Functions are a powerful tool that can help you write clean, efficient, and maintainable code. By breaking down complex problems into smaller pieces and encapsulating related code in functions, you can make your code more organized and easier to understand.

As you continue to learn programming, you will encounter more advanced concepts related to functions, such as recursion, anonymous functions (lambda functions), and higher-order functions. Keep practicing and experimenting with functions to become more comfortable with them and enhance your programming skills.