Functions in Python

Lesson Introduction

Welcome to the lesson on recalling functions in Python. Functions are fundamental building blocks that allow for code modularity, reusability, and better organization. Understanding functions helps you write cleaner and more maintainable code.

The goal of this lesson is to refresh your memory on defining and calling functions effectively in Python.

Functions: Declaration and Definition

In Python, a function is defined directly using the def keyword. There is no need for a separate declaration step. This makes defining and using functions straightforward and efficient.

A function definition provides the function's actual body and specifies what the function does when it is called. Functions can receive any number of arguments separated by commas.

Consider these function definitions in our code snippet:

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

def greet(name):
    print(f"Hello, {name}!")

if __name__ == "__main__":
    pass

The add function returns the sum of the two input parameters, while the greet function prints a greeting message. The pass statement in the if __name__ == "__main__": block indicates an empty block of code that does nothing. It acts as a placeholder.

Using Functions

Once functions are defined, they can be called from the main body of the script or any other function.

Calling a function involves specifying the function name followed by arguments in parentheses. If a function does not have a return statement, it returns None by default.

In our code snippet, we call the add function from the main body:

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

def greet(name):
    print(f"Hello, {name}!")

if __name__ == "__main__":
    sum_ints = add(2, 3)
    sum_doubles = add(2.5, 3.5)

    greet("Alice") # Hello, Alice!

    print("Sum of ints:", sum_ints)       # Sum of ints: 5
    print("Sum of doubles:", sum_doubles) # Sum of doubles: 6.0

Here, add(2, 3) returns 5, and add(2.5, 3.5) returns 6.0. The results are then printed using print(). The greet("Alice") function doesn't return anything useful, so we call it without assigning its result to a variable.

As a reminder, if __name__ == "__main__": is a special block in Python that ensures certain code runs only when the script is executed directly, not when it's imported as a module in another script. It is considered a good practice to include this in your Python scripts.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal