Conteúdo do Curso
Python Functions Tutorial
Python Functions Tutorial
What Is Function?
Using functions in Python is highly beneficial as they allow you to call the same block of code multiple times without rewriting it, saving time and reducing errors. Moreover, they help break down complex tasks into smaller, manageable steps, with each function performing a specific action, making the code more readable and easier to maintain.
In simpler terms, functions are like breaking down tasks into smaller pieces that you can use repeatedly. This approach makes your program more convenient to write, change, and understand.
Defining a function
Let's define the simplest function in Python.
- First, use the
def
keyword; - Next, specify the function name - a unique identifier that represents the function. It follows variables' naming conventions, such as using lowercase letters and underscores (this convention is called snake_case);
- Use
():
after the function name - in these brackets, specify the function's arguments (parameters); - Then, specify the function body with the indented new line;
- After the function body, specify the return value of the function using different keywords such as
return
,assign
, oryield
; - Finally, use functions in code. To do so, call the function using its name and specifying its parameters.
Let's look at an example. We will create a simple function to print 'Hello, world!'
in the console and use this function in code by calling it.
# Specify the function name # The function doesn't require any parameters, so we simply use `():` def print_hello(): # Function body: we have to use indentation when defining it. print('Hello, world!') # The function doesn't return anything, so we don't need to write additional code # Call the function print_hello()
You may have noticed that we used the print()
function as the body of print_hello()
. It is a built-in function that prints text to the console. It takes a string as an argument, which we specify in the ()
brackets.
You might wonder why this function has no return value if it prints the message in the console.
In Python, a function can perform a task (in this case, printing a message) without necessarily returning a value. The presence or absence of a return
statement in a function depends on whether the function is intended to produce an output (return a value) that can be used in other parts of the program.
The print_hello()
function prints a string to the console, but we can't use this string in the program, manipulate it, or use it as input for other functions. Therefore, the print_hello()
function has no return value.
Obrigado pelo seu feedback!