Functions in Python: How to Create and Use Them Efficiently – Lesson 7

Funções no Python

Functions are one of the most important concepts in any programming language, and Python is no different. They enable code reuse, make programs more modular, and simplify maintenance. In this seventh lesson of the beginner Python course, I will show you how to create functions and use them correctly.

What are functions in Python?

A function is a block of code that performs a specific task and can be reused in different parts of the program. In Python, we use the def keyword to define functions. They can take arguments and return values.

Using functions makes code more organized and reduces repetition. It also means a single change to the function’s logic is automatically reflected everywhere in the program that uses it. This improves maintainability and makes future extensions easier.

Creating your first function

Let’s start with a simple example:

def greeting():
    print("Hello! Welcome to the Python course.")

greeting()

Here, we define a function called greeting, which simply displays a message in the console when called. This kind of function is useful for repetitive tasks that don’t require dynamic parameters.

Passing parameters to functions in Python

Functions can take parameters to make them more dynamic. See this example:

def greeting(name):
    print(f"Hello, {name}! Welcome to the Python course.")

greeting("Carlos")
greeting("Ana")

In this case, the greeting function accepts a name argument and uses it in the displayed message. This lets you customize the output based on the name provided.

Returning values from a function

In many cases, it is useful for a function to return a value. For that, we use the return keyword:

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

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

Here, the add function takes two numbers, calculates their sum, and returns the result. This gives you more flexibility, because you can store the returned value in a variable or use it in other operations.

Default arguments in functions

We can define default values for a function’s parameters. This lets the function be called without passing every argument.

def greeting(name="Visitor"):
    print(f"Hello, {name}! Welcome.")

greeting()  # Output: Hello, Visitor! Welcome.
greeting("Maria")  # Output: Hello, Maria! Welcome.

If no argument is passed, the function uses the defined default value. This feature is useful for avoiding errors when certain parameters can be optional.

Functions with multiple arguments

We can use *args to pass a variable number of positional arguments:

def add_all(*numbers):
    return sum(numbers)

print(add_all(1, 2, 3, 4, 5))  # Output: 15

This lets you create functions that accept varying amounts of data, making them more versatile.

And **kwargs to receive keyword arguments:

def show_data(**data):
    for key, value in data.items():
        print(f"{key}: {value}")

show_data(name="Carlos", age=30, city="São Paulo")

Lambda Functions

Python lets you create anonymous functions called lambda functions. They are useful for short, simple functions:

multiply = lambda x, y: x * y
print(multiply(3, 4))  # Output: 12

Lambda functions are widely used in situations where we need quick functions, such as filtering and sorting:

numbers = [5, 2, 9, 1, 5, 6]
sorted_numbers = sorted(numbers, key=lambda x: x)
print(sorted_numbers)  # Output: [1, 2, 5, 5, 6, 9]

Variable scope in Python functions

A variable’s scope determines where it can be accessed in the code. In functions, we have local and global variables.

x = 10  # Global variable

def my_function():
    x = 5  # Local variable
    print(x)

my_function()  # Output: 5
print(x)  # Output: 10

The x variable inside the function does not change the global x, because they are in different scopes.

If we want to modify a global variable inside a function, we use the global keyword:

x = 10

def change_global():
    global x
    x = 20

change_global()
print(x)  # Output: 20

This can be useful in some cases, but it should be used with caution to avoid unwanted side effects.

Conclusion

Functions make code more organized and reusable. Knowing how to use them correctly is essential to becoming a good Python programmer. In addition, using scopes and arguments correctly lets you create more efficient and flexible functions.

If you want to dive deeper into the subject, I recommend reading the official Python documentation on functions: https://docs.python.org/3/tutorial/controlflow.html#defining-functions.

Practice by creating your own functions and explore different possibilities!

Você também pode gostar

PT | EN