Conteúdo do Curso
Python Functions Tutorial
Python Functions Tutorial
Function Body
The function body refers to the block of code contained within a function. It is part of the function definition where you write the instructions or statements that define the function's behavior.
Previously, we used mathematical formulas and the print()
function as the body in earlier chapters. However, the function body can be more complex, containing loops, if-else
statements, keywords, or other code to implement necessary logic.
We must use one indentation to define the function body. Indentation in Python refers to the spacing of code lines to define the structure and hierarchy of the code. In the context of functions, indentation defines the function's body, including all the statements executed when the function is called.
Example: Cat's Health Level
Write a function that determines a cat's health level based on the amount of calories it consumes daily. Consider the following conditions:
- If the cat consumes less than
200
calories per day, the health level is"low"
. - If the cat consumes between
200
and400
calories per day, the health level is"average"
. - If the cat consumes more than
400
calories per day, the health level is"high"
.
def health_level_for_cat(calories_per_day): # Use one indentation to create function body if calories_per_day < 200: health_level = 'Low' elif 200 <= calories_per_day <= 400: health_level = 'Average' else: health_level = 'High' message = f"The cat's health level based on calorie intake is {health_level}." return message # Example usage of the function print("Cat Felix:", health_level_for_cat(187)) print("Cat Tom:", health_level_for_cat(301)) print("Cat Oggy:", health_level_for_cat(404))
The function's body begins with the function definition. Inside, an if-else
statement determines the cat's health level based on daily calorie intake. After evaluating the condition, the function constructs a message reflecting the health level and returns it as the function's output.
In this example, the function assesses the cat's health level based on calorie consumption and generates a corresponding message, which is then printed as the function's output.
Obrigado pelo seu feedback!