Contenido del 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.
We have already used mathematical formulas and the print()
function as the body in the previous chapters. However, the function body can be more complex, containing loops, if-else
statements, keywords, or other code to realize necessary logic.
We have to 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 daily_calories_for_cat = 300 result = health_level_for_cat(daily_calories_for_cat) print(result)
The function's body starts with the definition of the function, and inside the function, an if-else
statement is used to determine the cat's health level based on the daily calorie intake. Following the conditional statement, the function forms a message based on the health level and returns it as the result of the function.
In this specific case, depending on the amount of calories, the function determines the cat's health level and generates a message accordingly, which is then printed as the output of the function.
¡Gracias por tus comentarios!