immagine python non disponible

In all programming languages, one of the most important aspects is code organization and readability. In Python, as in many other languages, this goal is also achieved through the use of functions.

By convention, all the code we write is executed within a main function, often called main. However, we can—and should—split our code into multiple functions to simplify maintenance and encourage reuse.

What are functions in Python?

The function definition in Python is done using the def keyword, followed by the function name and parentheses. There are two main types of functions:

  • Functions with a return value
  • Functions without a return value

Let’s look at both types in detail.

Functions with a return value

These functions return a result to the caller using the return keyword. They are useful when we need to use the output of a computation.

def compare_x_and_y(x, y) -> bool:
    if x > y:
        return True
    else:
        return False

Functions without a return value

These functions do not return any value. They are used to perform operations such as printing to the screen or modifying global variables, without needing to return a result.

def print_even_numbers(numbers):
    for elem in numbers:
        if elem % 2 == 0:
            print(elem)

Conclusion

In this article, we explored the function definition in Python, highlighting the difference between functions with and without a return value. Functions are a fundamental tool for writing clean, reusable, and testable code.

In the next tutorials, we’ll cover more advanced use cases of functions, including optional parameters, nested functions, and lambda expressions.

You can find the example code at this link.

Di admin

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *