Python

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

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!

Vinicius Sodré

Formado em Ciência da Computação pela Unicarioca, desenvolvedor de software com 15 anos de experiência em grandes empresas nacionais e multinacionais. Vinicius está à frente deste blog, feito de desenvolvedor para desenvolvedores de iniciantes a experientes.

Compartilhar
Publicado por:
Vinicius Sodré

Posts Recentes

Python Web Frameworks: A Complete Guide

Web development has evolved significantly in recent years, and Python frameworks are at the forefront…

1 year atrás

Python for AI: Master the Path to Artificial Intelligence

Artificial intelligence is revolutionizing every sector of society, from enterprise applications to everyday solutions. At…

1 year atrás

Tuples and Sets in Python: When to Use Each One – Lesson 11

In this lesson of the Python mini course, I want to cover two collection types…

1 year atrás

Dictionaries in Python: Everything You Need to Know – Lesson 10

Among Python's most versatile data structures, dictionaries stand out. They help us represent structured data…

2 years atrás

Lists in Python: Everything You Need to Know – Lesson 9

In this ninth lesson of the mini course, I want to talk about one of…

2 years atrás

Variable Scope in Python: Understand It and Get Rid of Bugs – Lesson 8

Understanding variable scope in Python is essential to avoid errors and write more predictable programs.…

2 years atrás

Este blog utiliza cookies. Se você continuar assumiremos que você está satisfeito com ele.

Leia Mais...